The new XML API that comes with Linq to XML has some peculiar ways of handling the XML declaration (aka the XML prolog). Take a look at this sample:
You might expect the XML declaration to be written to the console, but the actual output is without.
The XDocument.Save method on the other hand will always output the prolog. You can specify a filename or TextWriter to save your XML string to. Since Console.Out is a TextWriter instance simply change the last line to
and watch the output change to:
The prolog is now:
<?xml version=”1.0″ encoding=”IBM437″?>
So, what gives? We specified a certain encoding, but the encoding of the TextWriter instance is used. This is definitely something to take into account, as you cannot rely on your XDeclaration values to prevail.
Fixing the above is done by setting the output encoding explicitly:
What if you want to have a string value with the prolog?
Also, when you specify the XML version to be 1.1 in the declaration, the output will still give you version=”1.0″. Reflector reveals that the all overloads of the XDocument.Save implementation eventually call XmlTextWriter.WriteStartDocument that has the following line:
This clearly shows the hardcoded 1.0 version. Your XDeclaration’s version is ignored.
BTW, if you would like to get rid of the XML declaration when you use the Save method, you need a bit of a work-around. The Save methods accepts a SaveOptions enumeration, but this enum only lets you disable the formatting of the XML. Here’s how you would omit the declaration:
There you go.