HOWTO · Csharp
How to Deserialize XML to Object in C#
In this tutorial, learn the different methods of deserializing an xml to C# object with examples. Use the paste special feature of Visual Studio, xsd tool, and type the equivalent class in C#.
On this page
To deserialize XML into a C# object, define a class whose members match the document and use XmlSerializer. You can write that class yourself, generate it from an XML sample with Visual Studio Paste Special, or generate it from an XML schema with the XSD tool. Class generation creates a type; deserialization is the separate step that reads XML into an instance of that type.
Use Manually Typed Classes to Deserialize XML to a C# Object
For XML such as <Company><Employee name="Ana" age="30" /></Company>, the root element maps to a Company type, repeated Employee elements map to a collection, and the name and age attributes map to properties marked with XmlAttribute. Match element and attribute names and account for namespaces when the document uses them; XmlSerializer uses these mappings to read the document into the object graph.
Run this complete example:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
public class Company
{
[XmlElement("Employee")]
public List<Employee> Employees { get; set; } = new List<Employee>();
}
public class Employee
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("age")]
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
const string xml = "<Company><Employee name=\"Ana\" age=\"30\" /><Employee name=\"Bo\" age=\"32\" /></Company>";
var serializer = new XmlSerializer(typeof(Company));
using (var reader = new StringReader(xml))
{
var company = (Company)serializer.Deserialize(reader);
Console.WriteLine($"Employees: {company.Employees.Count}; first: {company.Employees[0].Name}, {company.Employees[0].Age}");
}
}
}
Employees: 2; first: Ana, 30
In an application that reads a file, pass a StreamReader for that file to Deserialize instead of the StringReader. XmlSerializer.Deserialize returns an object; cast it to the root type expected by the serializer, as this example does with Company. Deserialization reads XML into an object; serialization performs the reverse operation and writes an object as XML. If a value or element name differs from the class mapping, adjust the type or its serialization attributes to reflect the document.
Use Visual Studio Paste Special to Generate C# Classes from XML
Paste Special can create a starting class model from a representative XML sample. Copy the XML document, open or create a C# file in Visual Studio, then select Edit > Paste Special > Paste XML As Classes. The screenshot shows the command under the Edit menu’s Paste Special submenu.
The screenshot shows Paste XML As Classes in the expanded Edit > Paste Special menu.
Use the generated classes as the target types for XmlSerializer; the menu command does not read a document into an object. Review generated member names and attributes against the actual XML, especially when documents contain namespaces, optional fields, or repeated elements. The exact generated shape can depend on the sample, so treat it as a draft and keep any required adjustments in your project. If the menu item is not available in your environment, use the manual mapping above or the schema workflow below; this article does not assume a particular Visual Studio version or workload.
Use the XSD Tool to Generate C# Classes from XML
The XSD workflow has two distinct conversions: first produce an XML schema from a representative XML document, then generate C# classes from that schema. With the files in a working directory, the command sequence is xsd test.xml followed by xsd /c test.xsd. The first command writes a schema file, and the second requests C# class generation from that schema. These commands illustrate the tool’s inputs and order; availability and invocation can vary with the installed development environment, so use the XSD tool documentation supplied for that environment rather than assuming an installation path.
Generated class and member names may differ from hand-written names, but the XML mapping metadata is what lets XmlSerializer match document elements and attributes. After generation, reference the resulting classes in the application and deserialize the XML document into the generated root type using the same XmlSerializer pattern shown above. Generating a schema or source file alone does not create a populated object. Choose manual classes for a small stable format, Paste Special when working from an XML sample in the IDE, or the schema route when an XSD is part of the workflow or should guide generated types.