Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

26 Feb 2008

Writing Xml without the XmlDeclaration

Consider the following xml file:

<?xml version="1.0" encoding="utf-8" ?>
<!-- some comment -->
<root>
</root>
<!-- another comment -->

If you look at the Well-Formed XML Documents section in the XML specification you see that a well-formed document is defined as:

[1] document ::= prolog element Misc*

Since there is only 1 root element (ever), i assumed that if you Load this file with XmlDocument their would be only one XmlNode in the document ChildNodes. In reality there ChildNodes.Count returns 4.

The simplest way to write this XmlDocument without the declaration would be as following:

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.OmitXmlDeclaration = true;
xmlWriterSettings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(@"result.xml", xmlWriterSettings))
{
	xmlDoc.WriteTo(writer);
}