Last active
December 16, 2015 01:39
-
-
Save forcewake/5356401 to your computer and use it in GitHub Desktop.
XML deserialiser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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