Sometimes working with pure XML is our only option and we may just want it as clean as it can be. I usually use the XmlDocument object to load and/or create the XML and manipulate it and then at the end of the day, I'll use the InnerXml property to get pure XML, which I usually save to a file or do something with or I may just be serializing a Serializable object to XML.

The XmlDocument object by default assigns a namespace to the XML string and also includes the declaration as the first line of the XML document. I definitely do not need or use those, therefore, I need to remove them. Here is how you go about doing just that.

 

Removing the XML declaration

 

XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
StringWriter stringWriter = new StringWriter();
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
{
    serializer.Serialize(xmlWriter, request);
}
string xmlText = stringWriter.ToString();

 

Removing/Setting the namespace

 

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");

XmlSerializer serializer = new XmlSerializer(typeof(object));
StringWriter stringWriter = new StringWriter();
using(XmlWriter writer = new XmlTextWriterFormattedNoDeclaration(stringWriter ))
{
    serializer.Serialize(writer, this, ns);
}
string xmlText = stringWriter.ToString();