APEXA, LLC
Blog Gallery Contact

C# Xml Serialization to String & Deserialization

Blog Date: Thursday, May 8, 2008

 Recent Blogs << Back

XML, XSD.exe, C# and WCF Data Contracts 5/1/2008

String formatting in C# .NET and SQL Server 5/2/2008

How to uninstall an instance of SQL Server 2005 ma 5/4/2008

 More...
 

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

Home | Gallery | Contact | IT Consulting | Web Marketing | Search Engine Optimization | Web Design & CMS | My Blog on C# .NET

Site Map | Copyright 2007 Web Design web design | Developed by APEXA, LLC

APEXA, LLC