我在使用.SelectMony 挖掘xml文件时遇到问题
xml结构是
<data>
<request>
<type>LatLon</type>
<query>Lat 48.85 and Lon 2.35</query>
</request>
<current_condition>
<observation_time>12:38 PM</observation_time>
<isdaytime>yes</isdaytime>
<temp_C>16</temp_C>
<temp_F>61</temp_F>
<weatherCode>116</weatherCode>
<weatherIconUrl>
<![CDATA[
http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png
]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[ Partly Cloudy ]]>
</weatherDesc>
<windspeedMiles>7</windspeedMiles>
<windspeedKmph>11</windspeedKmph>
<winddirDegree>20</winddirDegree>
<winddir16Point>NNE</winddir16Point>
<precipMM>0.0</precipMM>
<humidity>51</humidity>
<visibility>10</visibility>
<pressure>1018</pressure>
<cloudcover>75</cloudcover>
<FeelsLikeC>16</FeelsLikeC>
<FeelsLikeF>61</FeelsLikeF>
</current_condition>
<weather>
<date>2014-04-11</date>
<astronomy>
<sunrise>07:08 AM</sunrise>
<sunset>08:36 PM</sunset>
<moonrise>04:45 PM</moonrise>
<moonset>05:15 AM</moonset>
</astronomy>
</weather>
<data>
我正试图从天文学中获得数据,但我的结果集是空的
我的代码是:
var displayAll = (result.Descendants("data")
.Descendants("current_condition")
.SelectMany(astronomy => astronomy.Descendants("weather")
.Select(wd => new DisplayWeatherCurrentConditions()
{
data removed for clarity as many lines such as
PrecipMm = Sanitizer.GetSafeHtmlFragment((string) wd.Element("precipMM")),
AstronomyInfo = wd.Elements("astronomy").Select(
dwa => new DisplayWeatherAstronomy()
{
SunRise = (string) wd.Element("sunrise") ?? string.Empty,
SunSet = (string) wd.Element("sunset") ?? string.Empty
}
).ToList()
})
));
return displayAll;
在我出错的地方提供任何帮助都将不胜感激,因为我已经使用了很多变体,但似乎无法做到正确。
感谢
---------------------------------代码编辑-----------------------
我已经设法让代码以我想要的方式工作,不确定这是否是正确的方式,但这就是我所做的。
为类创建了一个构造函数,如下所示:
public DisplayWeatherCurrentConditions(DisplayWeatherAstronomy dwa)
{
SunRise = dwa.SunRise;
Sunset = dwa.SunSet;
}
public string SunRise { get; set; }
public string Sunset { get; set; }
然后将代码更改为
var displayAll = (from wd in result.Descendants("current_condition")
from ts in result.Descendants("astronomy")
最终能够添加天文学类的属性
SunRise = (string)ts.Element("sunrise") ?? string.Empty,
Sunset = (string)ts.Element("sunset") ?? string.Empty,
如果有比我更有经验的人可以改进这一点,请进行
只需删除.Descendants("data")
使用result.Descendants("current_condition")
,而且我在current_condition
中没有看到任何weather
元素,如果您想获得以weather
开头的元素,则需要使用
result.Descendants("current_condition")
.Descendants()
.Where(x => x.Name.ToString().StartsWith("weather"))
或者,如果您只想获得weather
元素,请使用result.Descendants("weather")