XmlDocument.Load Vs XmlDocument.LoadXml

Sergio picture Sergio · Nov 2, 2009 · Viewed 50.3k times · Source

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

The application was crashing, giving the following error:

"Data at the root level is invalid. Line 1, position 1"

After inspecting the XML and finding 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?

Answer

AdaTheDev picture AdaTheDev · Nov 2, 2009

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.

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.