Andrey Klochaniy
Andrey Klochaniy

Reputation: 135

Deserialize XML with different elements to separated lists

Could you please help me with deserialization of current xml:

<ObjectList>
  <Item Attr1="1"/>
  <Item Attr1="2"/>
  <DifferentItem Attr2="5"/>    
</ObjectList>

I want to deserialize it in structure like this

public class ObjectList
{
    public List<Item> Items { get; set; }
    public List<DifferentItem> DifferentItems { get; set; }
}

public class Item
{
    public string Attr1 { get; set; }
}

public class DifferentItem
{
    public string Attr2 { get; set; }
}

I tried attributes, but unsuccessfully

[XmlArray("ObjectList")]
[XmlArrayItem("Item", typeof(Item))]

How can I solve this? Thanks)

Upvotes: 2

Views: 57

Answers (2)

rmc00
rmc00

Reputation: 887

You need to use XML attributes to help map XML to classes and properties. Here's a console app I wrote with your XML, and it gets parsed OK. Notice how I used the XmlRoot and XmlElement attributes to map it.

public class Program
{
    public static void Main()
    {
        var serializer = new XmlSerializer(typeof(ObjectList));
        var xml = "<ObjectList><Item Attr1=\"1\" /><Item Attr1=\"2\" /><DifferentItem Attr2=\"5\" /></ObjectList>";

        using (var reader = new StringReader(xml))
        {
            var schedule = (ObjectList)serializer.Deserialize(reader);
        }
    }

    [XmlRoot("ObjectList")]
    public class ObjectList
    {
        [XmlElement("Item")]
        public List<Item> Items { get; set; }

        [XmlElement("DifferentItem")]
        public List<DifferentItem> DifferentItems { get; set; }
    }

    public class Item
    {
        [XmlAttribute("Attr1")]
        public string Attr1 { get; set; }
    }


    public class DifferentItem
    {
        [XmlAttribute("Attr2")]
        public string Attr2 { get; set; }
    }
}

Upvotes: 0

Alexander Petrov
Alexander Petrov

Reputation: 14241

Add attributes:

public class ObjectList
{
    [XmlElement("Item")]
    public List<Item> Items { get; set; }
    [XmlElement("DifferentItem")]
    public List<DifferentItem> DifferentItems { get; set; }
}

Upvotes: 2

Related Questions