我如何嵌套这个LINQ查询
本文关键字:LINQ 查询 嵌套 何嵌套 | 更新日期: 2023-09-27 18:06:14
我有一个来自web服务的XML文档,我正在尝试查询。但是,我不确定如何查询XML时,它有嵌套在其他元素中的元素。
下面是XML文件的一部分(我没有包括全部,因为它是一个很长的文件):
<response>
<display_location>
<full>London, United Kingdom</full>
<city>London</city>
<state/>
<state_name>United Kingdom</state_name>
<country>UK</country>
<country_iso3166>GB</country_iso3166>
<zip>00000</zip>
<magic>553</magic>
<wmo>03772</wmo>
<latitude>51.47999954</latitude>
<longitude>-0.44999999</longitude>
<elevation>24.00000000</elevation>
</display_location>
<observation_location>
<full>London,</full>
<city>London</city>
<state/>
<country>UK</country>
<country_iso3166>GB</country_iso3166>
<latitude>51.47750092</latitude>
<longitude>-0.46138901</longitude>
<elevation>79 ft</elevation>
</observation_location>
我可以查询"一次一个部分",但我正在从LINQ构建一个对象。例如:
var data = from i in weatherResponse.Descendants("display_location")
select new Forecast
{
DisplayFullName = i.Element("full").Value
};
var data = from i in weatherResponse.Descendants("observation_location")
select new Forecast
{
ObservationFullName = i.Element("full").Value
};
我的"Forecast"类基本上都是这样的属性:
class Forecast
{
public string DisplayFullName { get; set; };
public string ObservationFullName { get; set; };
//Lots of other properties that will be set from the XML
}
然而,我需要将所有的LINQ"组合"在一起,这样我就可以设置对象的所有属性。我读过嵌套LINQ,但我不知道如何将其应用于这种特殊情况。
问题:我如何去"嵌套/组合"LINQ,以便我可以读取XML,然后设置相应的XML属性?
一种可能的方法:
var data = from i in weatherResponse.Descendants("response")
select new Forecast
{
DisplayFullName = (string)i.Element("display_location").Element("full"),
ObservationFullName = (string)i.Element("observation_location").Element("full")
};
另一种方式…我更喜欢使用流畅风格的Linq扩展方法
var results = weatherResponse.Descendants()
.SelectMany(d => d.Elements())
.Where(e => e.Name == "display_location" || e.Name == "observation_location")
.Select(e =>
{
if(e.Name == "display_location")
{
return new ForeCast{ DisplayFullName = e.Element("full").Value };
}
else if(e.Name == "observation_location")
{
return new ForeCast{ ObservationFullName = e.Element("full").Value };
}
else
{
return null;
}
});