Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load XML from URL on XmlDocument()

Tags:

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.

like image 944
markzzz Avatar asked Sep 21 '11 08:09

markzzz


People also ask

Which method read XML documents from file URL for stream?

If your application needs to know which encoding is used to read the stream, consider using an XmlTextReader object to read the stream, and then use the XmlTextReader.

Which method of the XmlDocument class takes XML as string while loading?

LoadXml(String) Method.


1 Answers

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);
like image 176
spender Avatar answered Oct 26 '22 20:10

spender