Deserializing XML to Objects in C#

Solution 1:

Create a class for each element that has a property for each element and a List or Array of objects (use the created one) for each child element. Then call System.Xml.Serialization.XmlSerializer.Deserialize on the string and cast the result as your object. Use the System.Xml.Serialization attributes to make adjustments, like to map the element to your ToDoList class, use the XmlElement("todo-list") attribute.

A shourtcut is to load your XML into Visual Studio, click the "Infer Schema" button and run "xsd.exe /c schema.xsd" to generate the classes. xsd.exe is in the tools folder. Then go through the generated code and make adjustments, such as changing shorts to ints where appropriate.

Solution 2:

Boils down to using xsd.exe from tools in VS:

xsd.exe "%xsdFile%" /c /out:"%outDirectory%" /l:"%language%"

Then load it with reader and deserializer:

public GeneratedClassFromXSD GetObjectFromXML()
{
    var settings = new XmlReaderSettings();
    var obj = new GeneratedClassFromXSD();
    var reader = XmlReader.Create(urlToService, settings);
    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(GeneratedClassFromXSD));
    obj = (GeneratedClassFromXSD)serializer.Deserialize(reader);

    reader.Close();
    return obj;
}

Solution 3:

Deserialize any object, as long as the type T is marked Serializable:

function T Deserialize<T>(string serializedResults)
{
    var serializer = new XmlSerializer(typeof(T));
    using (var stringReader = new StringReader(serializedResults))
        return (T)serializer.Deserialize(stringReader);
}

Solution 4:

Well, you'd have to have classes in your assembly that match, roughly, the XML (property called Private, a collection property called ToDo, etc).

The problem is that the XML has elements that are invalid for class names. So you'd have to implement IXmlSerializable in these classes to control how they are serialized to and from XML. You might be able to get away with using some of the xml serialization specific attributes as well, but that depends on your xml's schema.

That's a step above using reflection, but it might not be exactly what you're hoping for.