AllramEst
AllramEst

Reputation: 1449

Reading xml child nodes in foreach loop

I want to read all the nodes in the xml. Reading the top node without the loop goes fine, but I want to read all the nodes to get all the different temperatures for each city. This is the xml:

<servers>
  <server name ="Stockholm">
    <!-- data from Google weather -->
    <name>Stockholm (Google)</name><!--Läser denna rad för tillfället-->
    <url>http://www.yr.no/place/sweden/stockholm/stockholm/forecast.xml</url>
    <xpath>/weatherdata/forecast/tabular/time/temperature</xpath>
  </server>
  <server name ="Göteborg">
    <name>Göteborg (Google)</name>    <url>http://www.yr.no/place/Sweden/V%C3%A4stra_G%C3%B6taland/Gothenburg/forecast.xml</url>
    <xpath>/weatherdata/forecast/tabular/time/temperature</xpath>
  </server>
  <server name =" Malmö">
    <name>Malmö (Google)</name>
    <url>http://www.yr.no/place/sweden/scania/malmö/forecast.xml</url>
    <xpath>/weatherdata/forecast/tabular/time/temperature</xpath>
  </server>
</servers>

My code so far:

XmlDocument serverDoc = new XmlDocument();
serverDoc.Load("ServerUrls.xml");
XmlNodeList xml = 
serverDoc.SelectNodes("servers/server");
foreach (var node in xml)
{

}

I know its not much. But cant seem to find information I can use properly. Been to MSDN and tried to figure it out from there, but to no result.

Thankful for all the help I can get.

enter image description here

Upvotes: 1

Views: 4812

Answers (1)

har07
har07

Reputation: 89325

As mentioned in the comment, you need to get URL of the XML where the actual temperature resides, as well as the corresponding XPath to locate the temperatures within the XML. Load XML from the URL into XmlDocument and then execute the XPath to extract the actual temperature values :

foreach (XmlNode node in xml)
{
    // get information needed to extract temprature i.e XML location, and the XPath :
    var loc = node.SelectSingleNode("url").InnerText;
    var xpath = node.SelectSingleNode("xpath").InnerText;

    // get temperature information
    var doc = new XmlDocument();
    doc.Load(loc);
    var temperatures = doc.SelectNodes(xpath);

    // iterate through temperatures and take action accordingly, f.e print the temperature 
    foreach(XmlNode temperature in temperatures)
    {
        Console.WriteLine(temperature.Attributes["value"].Value);
    }
}

Upvotes: 4

Related Questions