Skip to content

Instantly share code, notes, and snippets.

@meboz
Created March 14, 2014 00:24
Show Gist options
  • Save meboz/9539925 to your computer and use it in GitHub Desktop.
Save meboz/9539925 to your computer and use it in GitHub Desktop.
public interface IXml
{
T Deserialize<T>(string xml);
string Serialize(object o);
string Serialize(object o, XmlSerializerNamespaces ns);
}
public class Xml : IXml
{
public T Deserialize<T>(string xml)
{
var xs = new XmlSerializer(typeof(T));
var memoryStream = new MemoryStream(xml.ToUTF8ByteArray());
return (T)xs.Deserialize(memoryStream);
}
public string Serialize(object o)
{
XmlDocument doc = GetDoc(o);
return doc.InnerXml;
}
public string Serialize(object o, XmlSerializerNamespaces ns) {
var doc = GetDoc(o, ns);
return doc.InnerXml;
}
private static XmlDocument GetDoc(object o) {
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
return GetDoc(o, ns);
}
private static XmlDocument GetDoc(object o, XmlSerializerNamespaces ns) {
var ms = new MemoryStream();
var s = new XmlSerializer(o.GetType());
var doc = new XmlDocument();
s.Serialize(ms, o, ns);
ms.Position = 0;
doc.Load(ms);
return doc;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment