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);
}

This entry was posted on Tuesday, February 26th, 2008 at 20:16 and is filed under C#, XML. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.