2010-11-04 115 views
0

我希望这是有道理的。我有以下XML文档。C#,LINQ获取指定父元素的子元素

<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 
       }; 

这不过只检索 “仔”。

回答

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">元素应付。

+0

工作过,感谢您的时间。 – 2010-11-04 15:59:44

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中有空值。这可以让我们收集所有数据,即使其中有些数据是无效的,然后我们可以在以后处理垃圾。