Introduction

In this article, we will see how to serialize and deserialize an XML file to a C# object, and convert C# object into an XML file.

Serializing XML to C# Object

Let's understand how to convert an XML file into a C# object. Take note of the below small XML file to demonstrate.
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Company xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  3. <Employee name="x" age="30" />
  4. <Employee name="y" age="32" />
  5. </Company>
To convert this XML into an object, first you need to create a similar class structure in C#.
  1. [XmlRoot(ElementName = "Company")]
  2. public class Company
  3. {
  4. public Company()
  5. {
  6. Employees = new List<Employee>();
  7. }
  8. [XmlElement(ElementName = "Employee")]
  9. public List<Employee> Employees { get; set; }
  10. public Employee this[string name]
  11. {
  12. get { return Employees.FirstOrDefault(s => string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase)); }
  13. }
  14. }
  15. public class Employee
  16. {
  17. [XmlAttribute("name")]
  18. public string Name { get; set; }
  19. [XmlAttribute("age")]
  20. public string Age { get; set; }
  21. }
Your XML and C# objects are ready. Let's see the final step of converting XML into a C# object. To do that, you need to use System.Xml.Serialization.XmlSerializer to serialize it.
  1. public T DeserializeToObject<T>(string filepath) where T : class
  2. {
  3. System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
  4. using (StreamReader sr = new StreamReader(filepath))
  5. {
  6. return (T)ser.Deserialize(sr);
  7. }
  8. }
Use the XML file path and use this function. You should see that the XML is converted into a company object with two employee objects.

Deserializing a C# Object in XML

Create a C# object, such as a company with a few employees, and then convert it into an XML file.
  1. var company = new Company();
  2. company.Employees = new List<Employee>() { new Employee() { Name = "o", Age = "10" } };
  3. SerializeToXml(company, xmlFilePath);
  1. public static void SerializeToXml<T>(T anyobject, string xmlFilePath)
  2. {
  3. XmlSerializer xmlSerializer = new XmlSerializer(anyobject.GetType());
  4. using (StreamWriter writer = new StreamWriter(xmlFilePath))
  5. {
  6. xmlSerializer.Serialize(writer, anyobject);
  7. }
  8. }
The output should look like the below text after converting it into XML.
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <Company xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  3. <Employee age="10" name="o"/>
  4. </Company>

Conclusion

In this post, we learned how to serialize and deserialize an XML file to a C# object and vice versa.