XMLDocument wont accept space at the start of an XML Document.

Hi all,

I have the following xml document

--------------------------------------------------------------------------

(space here)

< xml version="1.0" encoding="UTF-8" >


<wfmcase>
<case_details>
<caseid>case id</caseid>
<archive_status/>
</case_details>
<error_status>
<error>error</error>
<error_type>type</error_type>
<error_message>message</error_message>
</error_status>
</wfmcase>

-------------------------------------------------------------------------------

If i leave a space before the first line in the xml document i get an error with the below code. If i remove the empty line at the start it runs fine.

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.PreserveWhitespace = false;

xmlDoc.Load("dsp_does_not_exist.xml");

The error i get is :

Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it. Line 2, position 3.

Is there a work around this Or is this a bug



Answer this question

XMLDocument wont accept space at the start of an XML Document.

  • radarman

    The error message is pretty clear. If you have an XML declaration (i.e. < xml version="1.0" >) in your XML document then it needs to be at the start of the document, white space before the XML declaration is not allowed. Only a BOM (byte order mark) could precede the XML declaration.

  • Preston Park

    This is not a bug. As Martin Honnen states, there are certain requirements proper XML documents must follow.

    The ideal situation is to make sure the source of these XML documents is producing them correctly.

    A workaround could be to pre-process the file using other .NET objects to remove any space at the start of the file.

    -Ryan / Kardax


  • XMLDocument wont accept space at the start of an XML Document.