System.Xml.XmlException: Unexpected XML declaratio

2019-09-21 17:49发布

问题:

I got this error while Parse an string to XDocument after edit and save it. But anyone can help me locate error position - The Line 1, position 10475. How can i get that position ???

System.Xml.XmlException: 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 1, position 10475.

if (storage.FileExists("APPSDATA.xml"))
{
  var reader = new StreamReader(new IsolatedStorageFileStream("APPSDATA.xml", FileMode.Open, storage));

  string xml = reader.ReadToEnd();
  var xdoc = XDocument.Parse(xml);//error here 
  reader.Close(); 

The XML is big, this is jus a part of it

<?xml version="1.0" encoding="UTF-8"?>
<Ungdungs>
  <Ungdung>
    <Name>HERE City Lens</Name>
    <Id>b0a0ac22-cf9e-45ba-8120-815450e2fd71</Id>
    <Path>/Icon/herecitylens.png</Path>
    <Version>1.0.0.0</Version>
    <Category>HERE</Category>
    <Date>Uknown</Date>
  </Ungdung>
  <Ungdung>
    <Name>HERE Transit</Name>
    <Id>adfdad16-b54a-4ec3-b11e-66bd691be4e6</Id>
    <Path>/Icon/heretransit.png</Path>
    <Version>1.0.0.0</Version>
    <Category>HERE</Category>
    <Date>Uknown</Date>
  </Ungdung>

回答1:

Make sure your <?xml tag is the first thing in the document (and that it doesn't have anything before that, this includes whitespace). You can have <?xml only once per document, so if you have a large chunk of XML and you have this tag repeated somewhere down the lines your document won't be valid.



回答2:

In my case this was related to the byte order mark - BOM. I opened the file in Notepad++ selected encoding "encode in UTF-8 without BOM" and was then able to see the annoying charater and delete it.



回答3:

This error might occur if you previously saved the xml file with the boolean 'append = true'. Make if 'false', it should work.