为什么"根级别的数据无效.第1行,位置1".对于XML文档?

CJ7*_*CJ7 23 .net xml xmldocument xmlreader

我正在使用第三方DLL,它通过互联网传输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>
Run Code Online (Sandbox Code Playgroud)

例外:

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:
Run Code Online (Sandbox Code Playgroud)

小智 47

我最终发现有一个字节标记异常并使用此代码将其删除:

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

  • 当然它应该是`xml = xml.Remove(0,_byteOrderMarkUtf8.Length);`作为`String.Remove(Int32,Int32)`的第二个参数`是要从`startIndex`开始删除的字符数.请参阅[MSDN docs](https://msdn.microsoft.com/en-us/library/d8d7z2kk%28v=vs.110%29.aspx#Anchor_2). (3认同)
  • 要使此代码在Windows Server 2012以及Windows 7上运行,我必须使用`if(xml.StartsWith(_byteOrderMarkUtf8,StringComparison.Ordinal))`.有关详细信息,请访问http://stackoverflow.com/a/19495964/1843329. (3认同)

E-M*_*Max 11

我可以给你两个建议:

  1. 看来你使用的是"LoadXml"而不是"Load"方法.在某些情况下,它对我有帮助.
  2. 您有编码问题.你能检查一下XML文件的编码并写出来吗?