Monday, 14 March 2011

Anonymous C# method for XML serialization

Following is an anonymous C# method which can be used to serialize any given object into XML.

public static string SerializeToXML(T obj)
{
string serializedContext;

System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());

StringWriter stwOutPut = new StringWriter(new StringBuilder());

serializer.Serialize(stwOutPut, obj);

serializedContext = stwOutPut.ToString();

//Replace tag
serializedContext = serializedContext.Replace("", " ");

serializedContext = serializedContext.Replace("\r\n", " ");

return serializedContext;
}

No comments:

Post a Comment