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

时间:2010-11-04 15:50:38

标签: 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>

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

我试过

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

然而,只检索“Aberdeen”。

2 个答案:

答案 0 :(得分: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;

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

答案 1 :(得分:1)

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中有空值,请使用语句。这使我们可以收集所有数据,即使其中一些数据无效,然后我们可以处理以后丢失垃圾。