29 marzo 2009

Generic code to serialize a DataTable

Just add this code in your project, and call to the XmlSerialize solution:

///
/// Gets the XML of the passed object.
///

public static string XmlSerialize(object obj)
{
// Validate argument 'obj'
if (obj == null)
throw new ArgumentNullException("obj", "Argument 'obj' is null");

XmlSerializer ser = new XmlSerializer(obj.GetType());
UTF8Encoding utf8 = new UTF8Encoding(false, false);
string xml = null;

using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(ms, utf8))
{
ser.Serialize(sw, obj);
xml = utf8.GetString(ms.GetBuffer());
}
}

return xml;
}




No hay comentarios: