System.Xml.XmlException: Unexpected XML declaration. The XML declaration must be the first

旧街凉风 提交于 2019-12-13 09:34:24

问题


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.



来源:https://stackoverflow.com/questions/18546494/system-xml-xmlexception-unexpected-xml-declaration-the-xml-declaration-must-be

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!