openshac
openshac

Reputation: 5165

How to serialize a XML node of repeated elements

I am trying to deserialize some XML into an array of items.

Here's the XML:

<?xml version=\"1.0\" encoding=\"utf-8\"?>
<items>
    <item>
        <name>John</name>
    </item>
    <item>
         <name>Jane</name>
    </item>
</items>

And my class:

[XmlRoot("item")]
public class Item
{
    [XmlElement("name")]
    public string Name { get; set; }
}

I then deserialize:

var xmlSerializer = new XmlSerializer(typeof(Item[]), new XmlRootAttribute("items"));
using (TextReader textReader = new StringReader(xmlString))
{
    var items = (Item[])xmlSerializer.Deserialize(textReader);
    var itemCount = items.Length;
}

itemCount is 0 (it should be 2).

There is a similar solution here: https://stackoverflow.com/questions/15544517 but it seem to work only when the XML node names are identical to the class names (mine differ in capitalisation).

What do I need to modify to ensure all the items deserialize?

Upvotes: 1

Views: 1964

Answers (2)

openshac
openshac

Reputation: 5165

The root node is <items>, so the Item class should not have the XmlRoot attribute, instead it should use the XmlType attribute:

[XmlType("item")]
public class Item
{
    [XmlElement("name")]
    public string Name { get; set; }
}

Upvotes: 0

Yanga
Yanga

Reputation: 3012

The Xml Root "items" is missing

Your class should be:

    [XmlRoot("items")]
    public class Items
    {
        [XmlElement("item")]
        public Item[] Item { get; set; }
    }
    [XmlRoot("item")]
    public class Item
    {
        [XmlElement("name")]
        public string Name { get; set; }
    }

And the code to deserialize:

        var xmlSerializer = new XmlSerializer(typeof(Items), new XmlRootAttribute("items"));
        using (TextReader textReader = new StringReader(xmlString))
        {
            var items = (Items)xmlSerializer.Deserialize(textReader);
            var itemCount = items.Item.Length;
        }

Upvotes: 1

Related Questions