Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

I am using a third-party DLL which transmits an XML document over the internet.

Why would the DLL be throwing the following exception?

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

Here are the first few lines of the XML Document:

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

Exception:

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: 
like image 634
CJ7 Avatar asked Jul 30 '13 12:07

CJ7


2 Answers

I eventually figured out there was a byte mark exception and removed it using this code:

 string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());     if (xml.StartsWith(_byteOrderMarkUtf8))     {         var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length-1;         xml = xml.Remove(0, lastIndexOfUtf8);     } 
like image 134
James Brankin Avatar answered Oct 31 '22 17:10

James Brankin


I can give you two advices:

  1. It seems you are using "LoadXml" instead of "Load" method. In some cases, it helps me.
  2. You have an encoding problem. Could you check the encoding of the XML file and write it?
like image 39
E-Max Avatar answered Oct 31 '22 16:10

E-Max