2010-11-04 66 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中有空值。這可以讓我們收集所有數據,即使其中有些數據是無效的,然後我們可以在以後處理垃圾。