繁体   English   中英

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

[英]C#, LINQ Getting Child elements of a Specified Parent Element

我希望这是有道理的。 我有以下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>

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

我试过了

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

但是,该操作仅检索“阿伯丁”。

最简单的方法可能是使用后续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;

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

var regionQuery = from item in xdoc.Descendants("Country")
                              let countryCode = item.Attribute("Name") ?? new XAttribute("Name", string.Empty)
                              where countryCode.Value == "UK"
                              from region in item.Descendants("Region")
                              let regionName = region.Attribute("Name") ?? new XAttribute("Name", string.Empty)
                              select new {Name = regionName};

如果您的xml中有一个空值,则让语句很方便。 这使我们可以收集所有数据,即使其中一些数据无效,也可以稍后处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM