gygabyte
gygabyte

Reputation: 226

C# XmlDocument select nodes returns empty

i am trying to work with http://api.met.no/weatherapi/locationforecast/1.9/?lat=49.8197202;lon=18.1673554 XML. Lets say i want to select all value attribute of each temperature element.

i tried this.

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

But i get nothing all the time. What am i doing wrong?

Upvotes: 0

Views: 3870

Answers (2)

br0therDave
br0therDave

Reputation: 100

The current single slash is targeting weatherdata under the root but the root is weatherdata.

Add a preceding slash to your xpath query to make it a double slash:

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

Double slashes tells xpath to select nodes in the document from the current node that match the selection no matter where they are.

or remove the preceding slash:

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

which looks for the whole path including the root.

Also, since you apparently want the value called value add this:

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

Since the value at of node.Attributes[0].Value may not be in the order you expect.

Upvotes: 1

Teddy Higgins
Teddy Higgins

Reputation: 140

Are you attempting to loop through each attribute?

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

Upvotes: 0

Related Questions