Search code examples
c#xmlxml-declaration

Saving ONLY xml header in xml document throws error


I'm trying to use the following code to create a basic xml document with ONLY a header.

XDeclaration xmlDec = new XDeclaration("1.0", "utf-8", "no");
XDocument xmlDoc = new XDocument(xmlDec);
XDocument.Save("c:\myxml.xml");

When creating an xml file I create a basic xml header and try to save the xml document with ONLY the header but I get the following error on the Save method (last line)...

Token EndDocument in state Document would result in an invalid XML document.

I think it has to do with the fact there is no XML data after the declaration and I'm trying to save it. But all I want to save is the declaration. Is that not possible?


Solution

  • A valid XML document must have a root element. This behavior is correct.

    The definition of a well-formed XML document can be read at: https://www.w3.org/TR/xml/#sec-well-formed