簡體   English   中英

C#XmlDocument選擇節點返回空

[英]C# XmlDocument select nodes returns empty

我正在嘗試使用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);
        }

但是我一直都一無所獲。 我究竟做錯了什么?

您是否要遍歷每個屬性?

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

當前的單個斜杠以根目錄下的天氣數據為目標,但根目錄是氣象數據。

在您的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處的值可能與您期望的順序不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM