Last active
December 24, 2015 14:09
-
-
Save justinAurand/6810357 to your computer and use it in GitHub Desktop.
Takes an object and serializes it into XML.
This file contains 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.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