xml.LoadData - Data at the root level is invalid. Line 1, position 1
Solution 1
The hidden character is probably BOM. The explanation to the problem and the solution can be found here, credits to James Schubert, based on an answer by James Brankin found here.
Though the previous answer does remove the hidden character, it also removes the whole first line. The more precise version would be:
string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}
I encountered this problem when fetching an XSLT file from Azure blob and loading it into an XslCompiledTransform object. On my machine the file looked just fine, but after uploading it as a blob and fetching it back, the BOM character was added.
Solution 2
Use Load()
method instead, it will solve the problem. See more
Solution 3
The issue here was that myString
had that header line. Either there was some hidden character at the beginning of the first line or the line itself was causing the error. I sliced off the first line like so:
xml.LoadXml(myString.Substring(myString.IndexOf(Environment.NewLine)));
This solved my problem.
Solution 4
I Think that the problem is about encoding. That's why removing first line(with encoding byte) might solve the problem.
My solution for Data at the root level is invalid. Line 1, position 1.
in XDocument.Parse(xmlString)
was replacing it with XDocument.Load( new MemoryStream( xmlContentInBytes ) );
I've noticed that my xml string looked ok:
<?xml version="1.0" encoding="utf-8"?>
but in different text editor encoding it looked like this:
?<?xml version="1.0" encoding="utf-8"?>
At the end i did not need the xml string but xml byte[]. If you need to use the string you should look for "invisible" bytes in your string and play with encodings to adjust the xml content for parsing or loading.
Hope it will help
Solution 5
I've solved this issue by directly editing the byte array. Collect the UTF8 preamble and remove directly the header. Afterward you can transform the byte[]to a string with GetString method, see below. The \r and \t I've removed as well, just as precaution.
XmlDocument configurationXML = new XmlDocument();
List<byte> byteArray = new List<byte>(webRequest.downloadHandler.data);
foreach(byte singleByte in Encoding.UTF8.GetPreamble())
{
byteArray.RemoveAt(byteArray.IndexOf(singleByte));
}
string xml = System.Text.Encoding.UTF8.GetString(byteArray.ToArray());
xml = xml.Replace("\\r", "");
xml = xml.Replace("\\t", "");

Chris
Updated on July 08, 2022Comments
-
Chris 6 months
I'm trying to parse some XML inside a WiX installer. The XML would be an object of all my errors returned from a web server. I'm getting the error in the question title with this code:
XmlDocument xml = new XmlDocument(); try { xml.LoadXml(myString); } catch (Exception ex) { System.IO.File.WriteAllText(@"C:\text.txt", myString + "\r\n\r\n" + ex.Message); throw ex; }
myString
is this (as seen in the output oftext.txt
)<?xml version="1.0" encoding="utf-8"?> <Errors></Errors>
text.txt
comes out looking like this:<?xml version="1.0" encoding="utf-8"?> <Errors></Errors> Data at the root level is invalid. Line 1, position 1.
I need this XML to parse so I can see if I had any errors.
-
Ricardo Appleton about 9 yearsOnce I was getting this error and it turned out to a '?' at the beggining. I just replaced it with a blank space and got it running... That might also happen if the file you're reading is in a different encoding than what you're expecting
-
B. Clay Shannon-B. Crow Raven over 8 yearsI'm using XDocument.Load(), and I've got the problem.
-
B. Clay Shannon-B. Crow Raven over 8 yearsI tried this, but in .NETPrehistoric (1.1), I tried to use "\r\n" in place of the then-unavailable Environment.NewLine. I got, "Specified argument was out of the range of valid values."
-
Shesha almost 7 years@Chris: I have tried your solution. I am getting below exception. System.ArgumentOutOfRangeException: StartIndex cannot be less than zero. Parameter
-
user1040975 over 6 yearsNot sure and I guess I'll have to keep looking, but when I do this _byteOrderMarkUtf8 = "". so it doesn't catch it. Ideas?
-
John Demetriou about 5 yearstried it, did not help. xml is coming from db for that matter
-
Mister Cook over 4 yearsEncoding.UTF8.GetString(Encoding.UTF8.GetPreamble()) evaluates to an empty string
-
liquidcow over 4 yearsHad the same issues as the above commenters. Using
xmlStartsWith(byteOrderMarkUtf8, StringComparison.Ordinal)
did the trick for me. Credit to Hans Passant: stackoverflow.com/a/19495964/38425 -
Cubelaster almost 4 yearsThank you a lot for this answer. I had this problem when taking the XML from Outlook attachment, because for some reason it changes the Encoding to Utf-8-BOM. No method I found of converting the encodings worked. Only by removeing that first phantom character did it work. Thanks again
-
dval almost 4 yearsIf your loading files, read file into string first. Else you get "XmlDocument does not contain a definition for 'StartsWith' error.
-
lexeme almost 4 yearsIt helped me with '?' (invisible) right before the
<?xml version="1.0" encoding="utf-8"?>
declaration. -
mknopf almost 4 yearsThis solved the issue for me, thank you VERY much, I've banged my head on this for awhile now.
-
hardyVeles over 3 yearsIt is a solution but bad one. This is Encoding issue, by writing and reading file, you actually performed encoding and decoding without being aware,since invoked overload of the Load method have default value for Encoding parameter (System.Text.Encoding encoding)
-
Shubhasish Bhunia over 3 yearsthank you sir for pointing it out, could you please correct me?
-
hardyVeles over 3 yearsYou should decode and encode the String, using methods of the Encoding class, there is no need (and sense) to use File methods or file system at all. Please, check: docs.microsoft.com/en-us/dotnet/api/…
-
ThanhLD over 3 yearsIts work for me. But in the loop, we need to check byteArray.IndexOf(singleByte) != -1 or not before remove it.
-
CLS almost 3 yearsIt seems XmlDocument.Load() takes care of file Encoding when it is consequently specified in header. When not, one may have to deal with StreamReader and XmlDocument.LoadXml and other tools.
-
Andrew Keeton almost 3 yearsI was in the same boat as @mknopf. BOMs should be illegal.
-
Rowan Berry almost 3 yearsFunction doesn't work with VB .net 3.5 (requires index & count)
-
user3424480 over 2 yearsI'd also recommend replacing the .Remove method with .Substring for improved performance.
int bomLength = _byteOrderMarkUtf8.Length;
xml = xml.Substring(bomLength, xml.Length - bomLength);