Thursday, April 3, 2008

Serialize objects with no xml decoration and no namespaces

I posted couple of blogs earlier that shows how to Serialize/Deserialize objects and serialize using SOAP formatter. Few times we would like to serialize just the pure xml part of the object with no namespaces and/or no xml declaration tag at the top. Take a look, here's how we can do it in memory (without writing to a file):


/// <summary>
/// Serializes object with no namespace and no <?xml ... > tag. Returns pure xml of the object
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
internal string SerializeObjectPureXML(Object obj)
{
string serialXML = "";

//Empty namespace
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
//Serialize the passed object
XmlSerializer xs = new XmlSerializer(obj.GetType());
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
// set XML writer settings
XmlWriterSettings xwSettings = new XmlWriterSettings();
xwSettings.OmitXmlDeclaration = true;
xwSettings.Indent = true;
xwSettings.CloseOutput = true;
// create xml using the settings
using (XmlWriter xw = XmlWriter.Create(sw, xwSettings))
{
xs.Serialize(xw, obj, ns);
// get the xml and clean up
serialXML = sb.ToString();
xw.Flush();
}
sw.Flush();
}
//
return serialXML;
}

Love coding!

1 comment:

Houssam Hamdan said...

Is it possible to get the same pure xml result using DataContractSerializer instead of XmlSerializer ?

Thank you.