How to de-serialize XML with many child nodes

有些话、适合烂在心里 提交于 2019-12-23 10:49:11

问题


If my XML is like this:

<Item>
    <Name>Jerry</Name>
    <Array>
        <Item>
            <Name>Joe</Name>
        </Item>
        <Item>
            <Name>Sam</Name>
        </Item>
    </Array>
</Item>

I can serialize it into this class:

[DataContract(Namespace = "", Name = "dict")]
public class Item
{
    [DataMember(Name = "Name")]
    public string Name { get; set; }
    [DataMember(Name = "Array")]
    public IEnumerable<Item> Children { get; set; }
}

But what if my XML is like this?

<Item>
    <Name>Jerry</Name>
    <Item>
        <Name>Joe</Name>
    </Item>
    <Item>
        <Name>Sam</Name>
    </Item>
</Item>

This does not work:

[DataContract(Namespace = "", Name = "Item")]
public class Item
{
    [DataMember(Name = "Name")]
    public string Name { get; set; }
    [DataMember(Name = "Item")]
    public IEnumerable<Item> Children { get; set; }
}

What is the right way to decorate the class?


回答1:


If you want control over xml, then XmlSerializer is the way to go, not DataContractSerializer. The latter simply lacks the fine-grained control that XmlSerializer offers; in this case for things like list/array layout - but even just xml attributes are a problem for DataContractSerializer. Then it is just:

public class Item {
    public string Name { get; set; }
    [XmlElement("Item")]
    public List<Item> Children { get; set; }
}
public class Item {
    public string Name { get; set; }
}

and:

var serializer = new XmlSerializer(typeof(Item));
var item = (Item) serializer.Deserialize(source);



回答2:


Try using CollectionDataContractAttribute Internally you should create a generic list of Items and decorate it as CollectionDataContractAttribute with appropriate parameters.



来源:https://stackoverflow.com/questions/8219700/how-to-de-serialize-xml-with-many-child-nodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!