在foreach循环中读取xml子节点

时间:2017-04-13 05:50:21

标签: c# xml web-services webforms

我想读取xml中的所有节点。在没有循环的情况下读取顶部节点很顺利,但我想读取所有节点以获得每个城市的所有不同温度。这是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>

到目前为止我的代码:

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

}

我知道它并不多。但似乎无法找到我可以正确使用的信息。去过MSDN并试图从那里弄清楚,但没有结果。

感谢我能得到的所有帮助。

enter image description here

1 个答案:

答案 0 :(得分:2)

如评论中所述,您需要获取实际温度所在的XML的URL,以及用于在XML中定位温度的相应XPath。将URL从URL加载到XmlDocument,然后执行XPath以提取实际温度值:

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