Search code examples
c#xmlxml-deserialization

Deserialize xml to List<T> with custom elementName


Today I am trying to deserialize some xml to an List<Status> were the XML elementname is completely different. The XML is, for example, as follows:

<root>
    <child id="1">Lorum</child>
    <child id="2">Ipsum</child>
    <child id="3">Dolor</child>
</root>

To convert this into a List<T>, it is possible to create objects with the same name as the elements are. But that is in my case, unwanted.

Below the code which I have copied from dotnetfiddle.net:

using System;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.IO;

[XmlRoot("root")]
public class Statuses : List<Status>
{

}

[XmlRoot("child")]
public class Status
{
    [XmlAttribute("id")]
    public int ID;

    [XmlText]
    public string Value;
}

public static class Program
{
    private static string xml = "<root><child id=\"1\">Lorum</child><child id=\"2\">Ipsum</child><child id=\"3\">Dolor</child></root>";

    public static void Main()
    {
        using (StringReader sw = new StringReader(xml))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Statuses));
            Statuses statuses = (Statuses)serializer.Deserialize(sw);

            Console.WriteLine(statuses.Count);
        }
    }
}

The question now is how to get the list filled easily.


Solution

  • Change the attribute for the child elements to XMLType

    [XmlType("child")]
    public class Status
    

    Xml has only one root, but multiple types.