简体   繁体   中英

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.

在此输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM