C#,LINQ获取指定父元素的子元素

Ali*_*ley 0 c# linq linq-to-xml

我希望这是有道理的.我有以下XML文档.

<PrinterDirectory>
  <Country Name="UK>
    <Region Name="Aberdeen" />
    <Region Name="Birmingham" />
    <Region Name="London" />
  </Country>
  <Country Name="France">
    <Region Name="Paris" />
    <Region Name="Bordeaux" />
  </Country>
</PrinterDirectory>
Run Code Online (Sandbox Code Playgroud)

例如,用于检索英国地区的LINQ是什么?

我试过了

varRegionQuery = from items in xdoc.Descendants("Country")
                 where items.Attribute("Name").Value == "UK"
                 select new
                 {
                    _Region = items.Element("Region").Attribute("Name").Value
                 };
Run Code Online (Sandbox Code Playgroud)

然而,这只能找回"阿伯丁".

Jon*_*eet 6

最简单的方法可能是使用后续from子句,如下所示:

var regionQuery = from items in xdoc.Descendants("Country")
                  where items.Attribute("Name").Value == "UK"
                  from region in items.Elements("Region")
                  select region.Attribute("Name").Value;
Run Code Online (Sandbox Code Playgroud)

请注意,这将处理多个<Country Name="UK">元素.