Ali Beasley
Ali Beasley

Reputation: 77

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

Upvotes: 0

Views: 1284

Answers (2)

Howel
Howel

Reputation: 218

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.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499770

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.

Upvotes: 6

Related Questions