Created
June 29, 2017 13:36
-
-
Save alastairtree/bdc3cfe1cb1fdd5b28f9e3636059ae9a to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
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