Wednesday, September 9, 2009

Using XmlSerializer without rendering document declaration or namespace

Using xmlSerializer to serialize an object will by default add the xml namespace and document declaration. <strong>Example</strong>:

<?xml version="1.0" encoding="Windows-1252"?>
<node xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" uID="12345">
...
</node>

But if all you want is to write out the xml fragment like:
<node uid="12345">
...
</node>

You need to configure the serializer before you use it. The following code will not render the document declaration or namespace.

public void SerializeWithNoDeclarationNoNamespace<T>(TextWriter writer, T theObject)
{
var settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NewLineHandling = NewLineHandling.Replace,
NewLineChars = Environment.NewLine,
OmitXmlDeclaration = true
};

using (var xmlWriter = XmlWriter.Create(writer, settings))
{
var xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add("", "");

new XmlSerializer(typeof(T)).Serialize(xmlWriter, theObject, xmlnsEmpty);
}

writer.WriteLine("");
}

No comments:

Post a Comment