Skip to content

Instantly share code, notes, and snippets.

@justinAurand
Last active December 24, 2015 14:09
Show Gist options
  • Save justinAurand/6810357 to your computer and use it in GitHub Desktop.
Save justinAurand/6810357 to your computer and use it in GitHub Desktop.
Takes an object and serializes it into XML.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
// Serialize data object into Xml format.
public StringWriter Serialize<T>(T data)
{
using (var stringWriter = new Utf8StringWriter())
using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true }))
{
var xmlSerializer = new XmlSerializer(typeof(T));
try
{
xmlSerializer.Serialize(xmlWriter, data);
}
catch (SerializationException ex)
{
Console.Write(ex.ToString());
}
return stringWriter;
}
}
// For UTF-8 encoding during serialization.
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment