0

我正在尝试使用http://api.met.no/weatherapi/locationforecast/1.9/?lat=49.8197202;lon=18.1673554 XML。假设我想选择每个温度元素的所有值属性。

我试过这个。

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

但我一直什么都得不到。我究竟做错了什么?

4

2 回答 2

1

当前的单斜杠针对的是根下的天气数据,但根是天气数据。

在您的 xpath 查询中添加前面的斜杠以使其成为双斜杠:

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

双斜杠告诉 xpath 从当前节点中选择文档中与选择匹配的节点,无论它们在哪里。

或删除前面的斜杠:

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

它寻找包括根在内的整个路径。

此外,由于您显然想要名为 value 的值,请添加以下内容:

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

由于 node.Attributes[0].Value 的值可能与您期望的顺序不同。

于 2016-12-15T20:07:35.840 回答
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);
            }
        }
于 2016-12-15T20:01:09.937 回答