2016-09-22 145 views
0

使用RestSharp庫反序列化XML時,如果我有一個包含具有同名屬性的嵌套元素的元素,則父元素將採用該嵌套屬性值元素 - 我怎樣才能防止這種情況發生?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.Style = "bold"但我希望Foo.Style = null。如何防止父元素獲取子元素屬性值?

+0

你確定你想要一個類之間的循環?另外,請說明你是如何反序列化XML的,因爲我必須用'[XmlRoot(「foo」)]'來標記'Foo'才能使它工作,並且在那之後 - 它可以正常工作,'反序列化'Foo '爲空,它有兩個'Bar's,而第一個具有正確的'style'。 – kiziu

+0

我正在使用RestSharp庫檢索和反序列化XML - 特別是遵循[recommended](https://github.com/restsharp/RestSharp/wiki/Recommended-Usage)方法,其中我打電話像執行() ' – kin3tik

+0

我已更新帖子以更清楚地反映結構的基礎。 – kin3tik

回答