Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing XML to Objects in C#

So I have xml that looks like this:

<todo-list>   <id type="integer">#{id}</id>   <name>#{name}</name>   <description>#{description}</description>   <project-id type="integer">#{project_id}</project-id>   <milestone-id type="integer">#{milestone_id}</milestone-id>   <position type="integer">#{position}</position>    <!-- if user can see private lists -->   <private type="boolean">#{private}</private>    <!-- if the account supports time tracking -->   <tracked type="boolean">#{tracked}</tracked>    <!-- if todo-items are included in the response -->   <todo-items type="array">     <todo-item>       ...     </todo-item>     <todo-item>       ...     </todo-item>     ...   </todo-items> </todo-list> 

How would I go about using .NET's serialization library to deserialize this into C# objects?

Currently I'm using reflection and I map between the xml and my objects using the naming conventions.

like image 852
Justin Bozonier Avatar asked Oct 22 '08 16:10

Justin Bozonier


People also ask

What is Deserializing XML?

Deserialization is the process of reading an instance of an XML document and constructing an object that is strongly typed to the XML Schema (XSD) of the document. Before deserializing, an XmlSerializer must be constructed using the type of the object that is being deserialized.


1 Answers

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.

like image 180
Dan Goldstein Avatar answered Sep 19 '22 14:09

Dan Goldstein