C# Convert XML to an object or list of an object
Instead of doing my normal “write up an object and then parse the xml into it’s properties”, I decided to have a look at the XML deserialiser (well, deserializer in C# itself) – which has worked, and has saved me a lot of time.
Obviously you will need to create your object first, so here’s a person one:
[XmlRoot(ElementName = "person")]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Note the XmlRoot attribute – you will need to set this to the XML node that contains your properties.
Next you will need an XML document, here’s my sample one:
<people> <person> <FirstName>Daniel</FirstName> <LastName>Wylie</LastName> </person> <person> <FirstName>Jhon</FirstName> <LastName>Smith</LastName> </person> <person> <FirstName>Sam</FirstName> <LastName>Brown</LastName> </person> </people>
And of course, the XML Deserialiser class
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace SampleApplication.Common
{
public class Convertors
{
/// <summary>
/// Converts a single XML tree to the type of T
/// </summary>
/// <typeparam name="T">Type to return</typeparam>
/// <param name="xml">XML string to convert</param>
/// <returns></returns>
public static T XmlToObject<T>(string xml)
{
using (var xmlStream = new StringReader(xml))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(XmlReader.Create(xmlStream));
}
}
/// <summary>
/// Converts the XML to a list of T
/// </summary>
/// <typeparam name="T">Type to return</typeparam>
/// <param name="xml">XML string to convert</param>
/// <param name="nodePath">XML Node path to select <example>//People/Person</example></param>
/// <returns></returns>
public static List<T> XmlToObjectList<T>(string xml, string nodePath)
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
var returnItemsList = new List<T>();
foreach (XmlNode xmlNode in xmlDocument.SelectNodes(nodePath))
{
returnItemsList.Add(XmlToObject<T>(xmlNode.OuterXml));
}
return returnItemsList;
}
}
}
Usage:
var List<Person> = Convertors.XmlToObjectList<Person>(PeopleXML (Load how you wish), "//People/Person");






