如何嵌套此LINQ查询?

use*_*993 0 c# xml linq linq-to-xml

我有一个来自我正在尝试查询的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>
Run Code Online (Sandbox Code Playgroud)

我可以一次查询"一个部分"但我正在从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
           };
Run Code Online (Sandbox Code Playgroud)

我的"预测"类基本上只是充满了这样的属性:

class Forecast
{
    public string DisplayFullName { get; set; };
    public string ObservationFullName { get; set; };
    //Lots of other properties that will be set from the XML
}
Run Code Online (Sandbox Code Playgroud)

但是,我需要将所有LINQ"组合"在一起,以便我可以设置对象的所有属性.我已经阅读了有关嵌套LINQ的内容,但我不知道如何将其应用于此特定情况.

问题:如何"嵌套/组合"LINQ,以便我可以读取XML,然后使用所述XML设置适当的属性?

har*_*r07 6

一种可能的方式:

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")
           };
Run Code Online (Sandbox Code Playgroud)