2013-07-30 48 views
17

我正在使用通過互聯網傳輸XML文檔的第三方DLL。爲什麼「根級數據無效,第1行,第1位」。對於XML文檔?

爲什麼DLL會拋出以下異常?在根級

數據是無效的。行1,位置1(見下文的 充分異常文本。)

下面是XML文檔的前幾行:

<?xml version="1.0" encoding="utf-8"?> <REQUEST> <HEADER> 
    <REQUESTID>8a5f6d56-d56d-4b7b-b7bf-afcf89cd970d</REQUESTID> 
    <MESSAGETYPE>101</MESSAGETYPE> 
    <MESSAGEVERSION>3.0.2</MESSAGEVERSION> 

例外:

System.ApplicationException was caught 
     Message=Unexpected exception. 
     Source=FooSDK 
     StackTrace: 
      at FooSDK.RequestProcessor.Send(String SocketServerAddress, Int32 port) 
      at Foo.ExecuteRequest(Int32 messageID, IPayload payload, Provider prov) 
      at Foo.SendOrder(Int32 OrderNo) 
     InnerException: System.Xml.XmlException 
      LineNumber=1 
      LinePosition=1 
      Message=Data at the root level is invalid. Line 1, position 1. 
      Source=System.Xml 
      SourceUri="" 
      StackTrace: 
       at System.Xml.XmlTextReaderImpl.Throw(Exception e) 
       at System.Xml.XmlTextReaderImpl.Throw(String res, String arg) 
       at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace() 
       at System.Xml.XmlTextReaderImpl.ParseDocumentContent() 
       at System.Xml.XmlTextReaderImpl.Read() 
       at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace) 
       at System.Xml.XmlDocument.Load(XmlReader reader) 
       at System.Xml.XmlDocument.LoadXml(String xml) 
       at XYZ.RequestProcessor.GetObjectFromXML(String xmlResult) 
       at XYZ.RequestProcessor.Send(String SocketServerAddress, Int32 port) 
      InnerException: 
+1

如何將XML文件在互聯網上傳播的? HTTP?如果是,請檢查a)文件是否有BOM,以及b)HTTP標頭是否也指定了非UTF8字符集。 –

回答

10

我可以給你兩個建議:

  1. 看來你使用的是「LoadXml」而不是「Load」方法。在某些情況下,它可以幫助我。
  2. 您有一個編碼問題。你能檢查XML文件的編碼並寫下來嗎?
+0

剛剛看到評論。是的,嘗試將文件編碼設置爲UTF8-WITHOUT-BOM –

+0

選項1適用於我。 – BENN1TH

35

我終於想通了,有一個字節的標誌異常,使用此代碼刪除它:

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); 
    if (xml.StartsWith(_byteOrderMarkUtf8)) 
    { 
     var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length-1; 
     xml = xml.Remove(0, lastIndexOfUtf8); 
    } 
+0

這工作完美在我的情況 – Ian1971

+0

謝謝,這是我的問題。 – MushyPeas

+0

這是零區char數組 - 我不得不使用xml = xml.Remove(0,_byteOrderMarkUtf8.Length-1); –

0

我有一個類似的問題進行解析時開始爲"<?xml version=\"1.0\" encoding=\"utf-16\"?>\n...

XML字符串我所做的只是更換所有有趣的字符如下:

var xmlData = [myvariable].GetElementsByTagName("[SpecifiedNode]")[0].InnerText.Replace("\n", "").Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "").Replace("<string>", "").Replace("\\", "").Replace("</string>", "").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "/");

相關問題