【问题标题】:Parsing xml with two identically-named elements使用两个同名元素解析 xml
【发布时间】:2014-01-20 15:12:29
【问题描述】:

我尝试将此 XML 天气信息解析到我的应用程序中。

<weather>
  <date>2014-01-03
  </date>
  <chanceofsnow>0</chanceofsnow>
  <totalSnowfall_cm>0.0</totalSnowfall_cm>
  <top>
    <maxtempC>-3</maxtempC>
    <maxtempF>27</maxtempF>
    <mintempC>-5</mintempC>
    <mintempF>24</mintempF>
  </top>
  <hourly>
    <time>100</time>
    <top>
      <tempC>-6</tempC>
      <tempF>20</tempF>
      <windspeedMiles>8</windspeedMiles>
      <windspeedKmph>13</windspeedKmph>
      <winddirDegree>213</winddirDegree>
      <winddir16Point>SSW</winddir16Point>
      <weatherCode>113</weatherCode>
      <weatherIconUrl><![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png]]>        </weatherIconUrl>
      <weatherDesc><![CDATA[Clear]]></weatherDesc>
    </top>
  </hourly>
</weather>

我使用下面的 C# 来解析它:

XElement XmlSneeuw = XElement.Parse(e.Result);

//current
listBoxVandaag.ItemsSource
    = from weather in XmlSneeuw.Descendants("weather")
      select new AlgemeneInformatie
      {
          Chance_of_Snow = weather.Element("chanceofsnow").Value,
          Total_Snowfall = weather.Element("totalSnowfall_cm").Value,
      };

//Current
listBoxVandaagTop.ItemsSource
    = from weather1 in XmlSneeuw.Descendants("top") 
      select new AlgemeneInformatieTop
      {
          Actueel_Top_maxtempC = weather1.Element("maxtempC").Value,
          Actueel_Top_mintempC = weather1.Element("mintempC").Value,
      };

但是现在我的 xml 中有 2 个 TOP 元素,所以这不起作用。做这个的最好方式是什么?这是解析此类信息的正确方法吗?

我使用这个网站作为参考: http://developer.nokia.com/Community/Wiki/Weather_Online_app_for_Windows_Phone

【问题讨论】:

标签: c# xml xml-parsing


【解决方案1】:

我建议使用 LINQ 和 XPath 查询 XML,例如 here

//...
var topElement = XmlSneeuw.XPathSelectElement("./weather/top")
//Create your min/max object
//...

【讨论】:

    【解决方案2】:

    你可以使用.Elements("top")如下,限制同名的子级别元素

    listBoxVandaagTop.ItemsSource = XmlSneeuw.Elements("top").Select( weather1=> new AlgemeneInformatieTop
          {
              Actueel_Top_maxtempC = weather1.Element("maxtempC").Value,
              Actueel_Top_mintempC = weather1.Element("mintempC").Value,
          });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      • 2021-12-29
      相关资源
      最近更新 更多