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.
- <?xml version="1.0" encoding="utf-8"?>
- <Company xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <Employee name="x" age="30" />
- <Employee name="y" age="32" />
- </Company>
To convert this XML into an object, first you need to create a similar class structure in C#.
- [XmlRoot(ElementName = "Company")]
- public class Company
- {
- public Company()
- {
- Employees = new List<Employee>();
- }
-
- [XmlElement(ElementName = "Employee")]
- public List<Employee> Employees { get; set; }
-
- public Employee this[string name]
- {
- get { return Employees.FirstOrDefault(s => string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase)); }
- }
- }
-
- public class Employee
- {
- [XmlAttribute("name")]
- public string Name { get; set; }
-
- [XmlAttribute("age")]
- public string Age { get; set; }
- }
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.
- public T DeserializeToObject<T>(string filepath) where T : class
- {
- System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
-
- using (StreamReader sr = new StreamReader(filepath))
- {
- return (T)ser.Deserialize(sr);
- }
- }
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.
- var company = new Company();
- company.Employees = new List<Employee>() { new Employee() { Name = "o", Age = "10" } };
- SerializeToXml(company, xmlFilePath);
- public static void SerializeToXml<T>(T anyobject, string xmlFilePath)
- {
- XmlSerializer xmlSerializer = new XmlSerializer(anyobject.GetType());
-
- using (StreamWriter writer = new StreamWriter(xmlFilePath))
- {
- xmlSerializer.Serialize(writer, anyobject);
- }
- }
The output should look like the below text after converting it into XML.
- <?xml version="1.0" encoding="UTF-8"?>
- <Company xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <Employee age="10" name="o"/>
- </Company>
Conclusion
In this post, we learned how to serialize and deserialize an XML file to a C# object and vice versa.