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