2008-09-05

Let me try how this posting business works

This is a simplest possible C# generic xml-serialization helper class from my core library, but it just might be the perfect candidate for my first post.

I can't wait to test my code formatting stylesheet :).
using System.Xml.Serialization;
using System.IO;


namespace NoBuggs.Core.Xml
{
/// <summary>
/// Provides helper methods for object Xml serialization/deserialization.
/// </summary>
/// <typeparam name="T">Type of the object which should be serialized.</typeparam>
public static class XmlHelper<T>
{
/// <summary>
/// Serializes the specified object instance to XML, and saves
/// it to a file with the specified fileName.
/// </summary>
/// <param name="instance">The instance of the object to serialize.</param>
/// <param name="fileName">Name of the file.</param>
public static void Serialize(T instance, string fileName)
{
XmlSerializer xml = XmlSerializerCache<T>.GetInstance();
using (StreamWriter sw = new StreamWriter(fileName))
{
xml.Serialize(sw, instance);
}
}

/// <summary>
/// Returns a string containing the serialized XML representation
/// of the passed object <paramref name="instance"/>.
/// </summary>
/// <param name="instance">The instance of the object to serialize.</param>
/// <param name="fileName">Name of the file.</param>
public static string Serialize(T instance)
{
XmlSerializer xml = XmlSerializerCache<T>.GetInstance();
using (StringWriter sw = new StringWriter())
{
xml.Serialize(sw, instance);
return sw.ToString();
}
}

/// <summary>
/// Given the actual Xml string, returns the deserialized object
/// of type T.
/// </summary>
public static T DeserializeString(string xml)
{
XmlSerializer instance = XmlSerializerCache<T>.GetInstance();
using (StringReader sr = new StringReader(xml))
{
return (T)instance.Deserialize(sr);
}
}

/// <summary>
/// Deserializes the XML data from the file with the
/// specified fileName, into a new instance of the specified type.
/// </summary>
/// <param name="fileName">Name of the file which contains the serialized object.</param>
/// <returns></returns>
public static T Deserialize(string fileName)
{
XmlSerializer xml = XmlSerializerCache<T>.GetInstance();
using (StreamReader sr = new StreamReader(fileName))
{
return (T)xml.Deserialize(sr);
}
}
}
}

Object xml serialization can be now done for any type:

SomeClass someObject = new SomeClass();
XmlHelper<SomeClass>.Serialize(someObject, "output.xml");

And deserialization also:
SomeClass someObject = XmlHelper<SomeClass>.Deserialize("output.xml");


If you want to post some code in your blog, check out http://www.manoli.net/csharpformat/format.aspx. It is a nice and quick C# to Html converter.

No comments: