.net – 为什么“根级别的数据无效.第1行,第1位.“用于XML文档?

前端之家收集整理的这篇文章主要介绍了.net – 为什么“根级别的数据无效.第1行,第1位.“用于XML文档?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用通过互联网传输XML文档的第三方DLL.

为什么DLL会抛出以下异常?

Data at the root level is invalid. Line 1,position 1. (see below for
full exception text.)

以下是XML文档的前几行:

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

例外:

  1. System.ApplicationException was caught
  2. Message=Unexpected exception.
  3. Source=FooSDK
  4. StackTrace:
  5. at FooSDK.RequestProcessor.Send(String SocketServerAddress,Int32 port)
  6. at Foo.ExecuteRequest(Int32 messageID,IPayload payload,Provider prov)
  7. at Foo.SendOrder(Int32 OrderNo)
  8. InnerException: System.Xml.XmlException
  9. LineNumber=1
  10. LinePosition=1
  11. Message=Data at the root level is invalid. Line 1,position 1.
  12. Source=System.Xml
  13. SourceUri=""
  14. StackTrace:
  15. at System.Xml.XmlTextReaderImpl.Throw(Exception e)
  16. at System.Xml.XmlTextReaderImpl.Throw(String res,String arg)
  17. at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
  18. at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
  19. at System.Xml.XmlTextReaderImpl.Read()
  20. at System.Xml.XmlLoader.Load(XmlDocument doc,XmlReader reader,Boolean preserveWhitespace)
  21. at System.Xml.XmlDocument.Load(XmlReader reader)
  22. at System.Xml.XmlDocument.LoadXml(String xml)
  23. at XYZ.RequestProcessor.GetObjectFromXML(String xmlResult)
  24. at XYZ.RequestProcessor.Send(String SocketServerAddress,Int32 port)
  25. InnerException:
我最终弄清楚有一个字节标记异常,并使用以下代码将其删除
  1. string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
  2. if (xml.StartsWith(_byteOrderMarkUtf8))
  3. {
  4. var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length-1;
  5. xml = xml.Remove(0,lastIndexOfUtf8);
  6. }

猜你在找的XML相关文章