【问题标题】:Reading xml child nodes in foreach loop在foreach循环中读取xml子节点
【发布时间】:2017-04-13 05:50:21
【问题描述】:

我想读取 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 并试图从那里弄清楚,但没有结果。

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

【问题讨论】:

  • 下一步,将获取每个城市的 元素的值,然后链接到另一个 xml 文件,并使用 元素的值来解析该 xml文件以获取实际温度读数。

标签: c# xml web-services webforms


【解决方案1】:

正如评论中提到的,您需要获取实际温度所在的 XML 的 URL,以及相应的 XPath 以在 XML 中定位温度。将 URL 中的 XML 加载到 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);
    }
}

【讨论】:

  • 谢谢先生。你的解决方案工作得很好!另一个我似乎无法理解的问题发生了。第一个下的两个温度场正确显示。无法弄清楚它是什么。有什么想法吗?图片在我原来的问题。编辑:背景似乎是透明的。
  • 修复了!所以没问题再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 2016-08-13
  • 1970-01-01
  • 2023-02-25
  • 1970-01-01
相关资源
最近更新 更多