20

I have this code :

string m_strFilePath = "http://www.google.com/ig/api?weather=12414&hl=it";

XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.LoadXml(m_strFilePath);

foreach (XmlNode RootNode in myXmlDocument.ChildNodes)
{
}

but when I try to execute it, I get this error :

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

Why? Where am I wrong? And how can I fix this problem on C#?

Also tried with :

myXmlDocument.Load(m_strFilePath);    

but I get :

Exception Details: System.Xml.XmlException: Invalid character in the given encoding. Line 1, position 503.

markzzz
  • 47,390
  • 120
  • 299
  • 507

2 Answers2

38

NOTE: You're really better off using XDocument for most XML parsing needs nowadays.

It's telling you that the value of m_strFilePath is not valid XML. Try:

string m_strFilePath = "http://www.google.com/ig/api?weather=12414&hl=it";
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.Load(m_strFilePath); //Load NOT LoadXml

However, this is failing (for unknown reason... seems to be choking on the à of Umidità). The following works (still trying to figure out what the difference is though):

var m_strFilePath = "http://www.google.com/ig/api?weather=12414&hl=it";
string xmlStr;
using(var wc = new WebClient())
{
    xmlStr = wc.DownloadString(m_strFilePath);
}
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlStr);
spender
  • 117,338
  • 33
  • 229
  • 351
  • It says Exception Details: System.Xml.XmlException: Invalid character in the given encoding. Line 1, position 503. – markzzz Sep 21 '11 at 08:47
  • It's got me stumped. Must be something to do with encoding, but can't get to the bottom of it. Anyone? – spender Sep 21 '11 at 08:59
  • This perplexes me, so I opened a question about it: http://stackoverflow.com/questions/7497371/xmldocument-load-fails-loadxml-works – spender Sep 21 '11 at 09:17
  • I believe if you URLEncode your string before you submit it, it should eliminate this issue. System.Web.HttpUtility.UrlEncode(URL, System.Text.Encoding.UTF8); – Danimal111 Nov 08 '16 at 20:12
  • Can you please see one of my [question](https://stackoverflow.com/questions/55430357/how-to-get-xml-web-service-response-in-c-sharp) regarding the xml response? – Moeez Mar 31 '19 at 05:29
6

You need to use Load() instead of LoadXML(). LoadXML tries to parse a string into XML, in this case your URL.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
Nicolai
  • 2,835
  • 7
  • 42
  • 52
  • Can you please see one of my [question](https://stackoverflow.com/questions/55430357/how-to-get-xml-web-service-response-in-c-sharp) regarding the xml response? – Moeez Mar 31 '19 at 05:29