Loading your XmlDocuments correctly.

by Dominic Zukiewicz 27. April 2007 15:28
Considering how much XML is used and the amount of code I've written to read/write XML, I still make a common mistake!

If you ever get this error:

System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.

Make sure you are using the correct method for the XmlDocument class. For example:

string xml = @"<xml version=""1.0""?><node><innerNode/></node>";

string filename = @"C:\\temp.xml";
StreamWriter sw = new StreamWriter(filename);
sw.Write(xml);
sw.Close();

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.LoadXml(filename);  // <-- Error right here!

This overload is for loading TEXT and not files.

So remember

- Load () for files and stream
- LoadXml() to load XML strings!

Easily mis-understood, so learn it or spend several hours debugging!!

 

Tags:

Framework | Xml

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar