简体   繁体   中英

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

I hope that makes sense. I have the following XML document.

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

What is the LINQ to retrieve just the regions of UK for example?

I've tried

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

That however only retrieves "Aberdeen".

The simplest way is probably to use a subsequent from clause, like this:

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;

Note that that will cope with multiple <Country Name="UK"> elements.

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

Let statements are handy in case you have a null value in your xml. This lets us gather all the data even if some of it is invalid and then we can deal with getting the junk out later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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