Skip to content

Instantly share code, notes, and snippets.

@alastairtree
Created June 29, 2017 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alastairtree/bdc3cfe1cb1fdd5b28f9e3636059ae9a to your computer and use it in GitHub Desktop.
Save alastairtree/bdc3cfe1cb1fdd5b28f9e3636059ae9a to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Util
{
public static class XmlUtil
{
public static XmlDocument SerializeToDocument(object input, string xmlNamespace = null)
{
if (input == null) throw new ArgumentNullException(nameof(input));
var xmlSerializer = new XmlSerializer(input.GetType(), xmlNamespace);
XmlDocument xmlDocument;
using (var memoryStream = new MemoryStream())
{
xmlSerializer.Serialize(memoryStream, input);
memoryStream.Position = 0;
var settings = new XmlReaderSettings {IgnoreWhitespace = true};
using (var xmlReader = XmlReader.Create(memoryStream, settings))
{
xmlDocument = new XmlDocument();
xmlDocument.Load(xmlReader);
}
}
return xmlDocument;
}
public static T DeserializeToObject<T>(string input)
{
if (input == null) throw new ArgumentNullException(nameof(input));
var xmlSerializer = new XmlSerializer(typeof(T));
var byteArray = Encoding.UTF8.GetBytes(input);
using (var stream = new MemoryStream(byteArray))
{
return (T)xmlSerializer.Deserialize(stream);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment