//New BSD License (BSD)
//http://twitterxml.codeplex.com/license
using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace TwitterXml.Utilities
{
public class XmlSerializerHelper
{
///
/// Deserializes an xml document back into an object
///
/// The xml data to deserialize
/// The type of the object being deserialized
/// A deserialized object
public static object Deserialize(XmlDocument xml, Type type)
{
XmlSerializer s = new XmlSerializer(type);
string xmlString = xml.OuterXml.ToString();
byte[] buffer = ASCIIEncoding.UTF8.GetBytes(xmlString);
MemoryStream ms = new MemoryStream(buffer);
XmlReader reader = new XmlTextReader(ms);
Exception caught = null;
try
{
object o = s.Deserialize(reader);
return o;
}
catch (Exception e)
{
caught = e;
}
finally
{
reader.Close();
if (caught != null)
throw caught;
}
return null;
}
///
/// Serializes an object into an Xml Document
///
/// The object to serialize
/// An Xml Document consisting of said object's data
public static XmlDocument Serialize(object o)
{
XmlSerializer s = new XmlSerializer(o.GetType());
MemoryStream ms = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(ms, new UTF8Encoding());
writer.Formatting = Formatting.Indented;
writer.IndentChar = ' ';
writer.Indentation = 5;
Exception caught = null;
try
{
s.Serialize(writer, o);
XmlDocument xml = new XmlDocument();
string xmlString = ASCIIEncoding.UTF8.GetString(ms.ToArray());
xml.LoadXml(xmlString);
return xml;
}
catch (Exception e)
{
caught = e;
}
finally
{
writer.Close();
ms.Close();
if (caught != null)
throw caught;
}
return null;
}
}
}