Tuesday, March 15, 2011

Serialize a class to XML

public string GetXML()
{
XmlSerializer objXMLSerializer = null;
StringWriter objStrW = null; // String writer to serialize the object to xml
String strXML; // Stores the serialized XML string
try
{
//Initilize the serializer
objXMLSerializer = new XmlSerializer(this.GetType()); // The serializer object
// Serialize the object
objStrW = new StringWriter();
objXMLSerializer.Serialize(objStrW, this);
// Retrieve the XML
strXML = objStrW.ToString().Replace(CommonConstants.CONST_UTF16, CommonConstants.CONST_UTF8);
return strXML;
}
catch (Exception ex)
{
//throw the exception to the calling function
throw ex;
}
finally
{
//Release the objects
objStrW.Close();
objXMLSerializer = null;
}
}

No comments: