Convert any serializable object in XML

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 608
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

public static string GetXmlFromObject(object objItem, string rootAttribute)
{
XmlSerializer xmlSer;
XmlSerializerNamespaces xmlNs = new XmlSerializerNamespaces();
MemoryStream memStream = new MemoryStream();

xmlNs.Add("", "");

xmlSer = new XmlSerializer(objItem.GetType(), new XmlRootAttribute(rootAttribute));
xmlSer.Serialize(memStream, objItem, xmlNs);

string xmlString = ASCIIEncoding.UTF8.GetString(memStream.ToArray(), 0, memStream.ToArray().Length);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
if (xmlDoc.SelectSingleNode(rootAttribute) != null)
return xmlDoc.SelectSingleNode(rootAttribute).OuterXml;

return string.Empty;
}

Comments or Responses

Login to post response