How to de-serialize XML with many child nodes

If my XML looks like this:

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

I can serialize it to 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; }
}

How to decorate a class?

+5
source share
2 answers

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

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);
+4
source

CollectionDataContractAttribute CollectionDataContractAttribute .

0

All Articles