如何在XmlDocument()上从URL加载XML

我有这个代码:

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) { } 

但是当我尝试执行它时,我收到此错误:

exception详细信息:System.Xml.XmlException:根级别的数据无效。 第1行,第1位。

为什么? 我哪里错了? 我怎样才能在C#上解决这个问题?

还试过:

 myXmlDocument.Load(m_strFilePath); 

但我得到:

exception详细信息:System.Xml.XmlException:给定编码中的字符无效。 第1行,第503位。

它告诉你m_strFilePath的值不是有效的XML。 尝试:

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

然而,这是失败的(原因不明……似乎在Umidità上窒息)。 以下工作(仍然试图弄清楚有什么区别):

 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); 

您需要使用Load()而不是LoadXML() 。 LoadXML尝试将字符串解析为XML,在本例中是您的URL。