2016-12-15 83 views
0

我试图用http://api.met.no/weatherapi/locationforecast/1.9/?lat=49.8197202;lon=18.1673554 XML工作。假设我想选择每个温度元素的所有值属性。C#的XmlDocument选择节点返回空

我想这一点。

 const string url = "http://api.met.no/weatherapi/locationforecast/1.9/?lat=49.8197202;lon=18.1673554"; 
     WebClient client = new WebClient(); 
     string x = client.DownloadString(url); 
     XmlDocument xml = new XmlDocument(); 
     xml.LoadXml(x); 

     XmlNodeList nodes = xml.SelectNodes("/weatherdata/product/time/location/temperature"); 
     //XmlNodeList nodes = xml.SelectNodes("temperature"); 

     foreach (XmlNode node in nodes) 
     {     
      Console.WriteLine(node.Attributes[0].Value); 
     } 

但是我什么都没有得到。我究竟做错了什么?

+0

所以大概这说明不文档中存在。也存在使用XDocument – mybirthname

+0

。我必须使用XmlDocument类。我必须为学校项目和必要的指定做这件事。 – gygabyte

回答

0

当前单斜杠的目标是根目录下的weatherdata,但根目录是weatherdata。

前斜线添加到您的XPath查询,使之成为双斜线:

XmlNodeList nodes = xml.SelectNodes("//weatherdata/product/time/location/temperature"); 

双斜杠告诉XPath来选择符合选择当前节点的文档中的节点,无论他们在哪里。

或删除前面的斜线:

XmlNodeList nodes = xml.SelectNodes("weatherdata/product/time/location/temperature"); 

看起来为全路径包括根。

而且,由于你显然希望所谓价值添加此值:

Console.WriteLine(node.Attributes["value"].Value); 

因为在node.Attributes的值[0] .value的可能不是你所期望的顺序。

0

你通过每个属性试图循环?

foreach (XmlNode node in nodes) 
     { 
      //You could grab just the value like below 
      Console.WriteLine(node.Attributes["value"].Value); 

      //or loop through each attribute 
      foreach (XmlAttribute f in node.Attributes) 
      { 
       Console.WriteLine(f.Value); 
      } 
     } 
+0

无处我猜。我一定要吗? – gygabyte

+0

编辑。看到你编辑你的问题 –