Skip to content

Instantly share code, notes, and snippets.

@forcewake
Last active December 16, 2015 01:39
Show Gist options
  • Save forcewake/5356401 to your computer and use it in GitHub Desktop.
Save forcewake/5356401 to your computer and use it in GitHub Desktop.
XML deserialiser
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace ConvertorApplication
{
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</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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment