【问题标题】:XML Deserialization - Parent element getting attribute value of childXML反序列化-父元素获取子元素的属性值
【发布时间】:2016-09-22 12:58:57
【问题描述】:

当使用 RestSharp 库反序列化 XML 时,如果我有一个包含嵌套元素的元素,该元素具有同名的属性,则父元素将采用嵌套元素的该属性值 - 如何防止这种情况发生?

我有几个类(比这个大,但这是一个简化的演示形式)设置为反序列化 XML。

[XmlType(AnonymousType = true)]
[XmlRoot(IsNullable = false)]
public class Base
{
    [XmlAttribute("title")]
    public string Title { get; set; }

    [XmlArray("base")]
    [XmlArrayItem("foo")]
    public List<Foo> Foos{ get; set; }

    public Base()
    {
        Foos = new List<Foo>();
    }
}

[XmlType(AnonymousType = true)]
public class Foo
{
    [XmlAttribute("style")]
    public string Style { get; set; }

    [XmlElement("bar")]
    public List<Bar> Bars { get; set; }

    public Foo()
    {           
        Bars = new List<Bar>();
    }
}

[XmlType(AnonymousType = true)]
public class Bar
{
    [XmlAttribute("style")]
    public string Style { get; set; }

    [XmlElement("foo")]
    public List<Foo> Foos{ get; set; }

    public Bar()
    {
        Foos = new List<Foo>();
    }
}

与 XML 类似:

<base>
    <foo>
        <bar style="bold" />
        <bar />
    </foo>
    <foo>
        <bar style="bold" />
        <bar />
    </foo>
</base>

反序列化时,我有一个 Foo 实例,其中 Foo.Style = "bold" 但我希望 Foo.Style = null。如何防止父元素取子元素属性值?

【问题讨论】:

  • 您确定要在课程之间循环吗?另外,请说明您究竟是如何反序列化该 XML,因为我必须用 [XmlRoot("foo")] 标记 Foo 才能使其工作,然后 - 它工作正常,反序列化的 Foostyle 为空,它有两个Bars,而第一个有正确的style
  • 我正在使用 RestSharp 库检索和反序列化 XML - 特别是遵循 recommended 方法,我调用类似 Execute&lt;Foo&gt;() 的方法
  • 我更新了帖子以更清楚地反映结构的基础。

标签: c# .net xml xml-serialization restsharp


【解决方案1】:

这似乎是 RestSharp 库的问题。

https://github.com/restsharp/RestSharp/issues/752

我还没有找到解决办法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多