tags:

views:

1700

answers:

4

I just came across with a problem using XmlDocument.LoadXml.

The application was crashing with the following error: "Data at the root level is invalid. Line 1, position 1"

After inspecting the XML and founding nothing wrong with it I googled a bit and found a tip to use XmlDocument.Load instead of XmlDocument.LoadXml.

I have tried it and it works perfectly.

My question is: What is the difference between the 2 methods and what could have cause one to work and the other to fail?

+9  A: 

XmlDocument.Load is used to load XML either from a stream, TextReader, path/URL, or XmlReader. XmlDocument.LoadXml is used to load the XML contained within a string variable

They're fundamentally different ways of loading XML, depending on where the XML is actually stored. So it sounds like you were using the wrong method for where your XML is.

AdaTheDev
+7  A: 

Were you trying to use XmlDocument.LoadXml and passing in the name of a file? It doesn't do that - it assumes that the string you pass in is the XML. So you might use:

doc.LoadXml("<root><child /><root>");

or

doc.Load("myfile.xml");

If that doesn't help, could you show your failing and working code? There are different ways you could have changed from using LoadXml to Load...

Jon Skeet
+2  A: 

Load() loads from a certain source, whereas LoadXml() loads directly from a string

Charlie Somerville
+1  A: 

Assuming your using XmlDocument.Load and XmlDocument.LoadXml in the right way this problem may be caused by Byte Order Mark.

This other question might be useful.

bruno conde