Skip to content

Instantly share code, notes, and snippets.

@cmillr
Created January 17, 2014 20:38
Show Gist options
  • Save cmillr/8480955 to your computer and use it in GitHub Desktop.
Save cmillr/8480955 to your computer and use it in GitHub Desktop.
This class contains only an extension method to all types that converts any arbitrary object to an XML tag tree.
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
public static partial class Converter
{
public static string ToXml<T>(this T TheObject)
{
var Serializer = new XmlSerializer(typeof(T));
var SerializerSettings = new XmlWriterSettings
{
Encoding = new UnicodeEncoding(false, false),
Indent = true,
OmitXmlDeclaration = true,
};
// these two lines prevent the root tag from being namespaced
var Ns = new XmlSerializerNamespaces();
Ns.Add("", "");
using (var Results = new StringWriter())
{
using (var Writer = XmlWriter.Create(Results, SerializerSettings))
Serializer.Serialize(Writer, TheObject, Ns);
return Results.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment