C# Xml Serialization to String & Deserialization
Blog Date:
Thursday, May 8, 2008
I wanted to make the XML text formatted as you would see inside an XML file. The only way I found was to just write it to a file first.
public static String Serialize(Object data)
{
string result = string.Empty;
System.Xml.Serialization.XmlSerializer x
= new System.Xml.Serialization.XmlSerializer(data.GetType()); //Serialization engine
string filename = System.IO.Path.GetTempFileName(); //Temporary file
System.IO.FileInfo fiFile = new System.IO.FileInfo(filename); //File information
// Create a temporary file for a formatted XML document
using (System.IO.StreamWriter sw = fiFile.CreateText())
{
x.Serialize(sw, data);
}
// Read out formatted XML
result = System.IO.File.ReadAllText(filename);
return result;
}
public static T Deserialize<T>(string text)
{
T data = default(T); //Type to return
System.Xml.Serialization.XmlSerializer x
= new System.Xml.Serialization.XmlSerializer(typeof(T)); //Serialization engine
string filename = System.IO.Path.GetTempFileName(); //Temporary file
System.IO.FileInfo fiFile = new System.IO.FileInfo(filename); //File information
// Create a temporary file for a formatted XML document
using (System.IO.StreamWriter sw = fiFile.CreateText())
{
sw.WriteLine(text);
}
// Now read out from a file stream
using (System.IO.FileStream fs
= new System.IO.FileStream(filename, System.IO.FileMode.Open))
{
data = (T)x.Deserialize(fs);
}
return data;
}
Custom XML Serialization and XPath Reading
This is a neat tool for testing reading your XML with XPath:
http://weblogs.asp.net/nleghari/articles/27951.aspx
Thursday, May 08, 2008 6:42:18 PM