Search code examples
c#linq-to-xmldescendant

Using LINQ to XML to match deeper descendant elements?


Suppose I have the following XML file:

<?xml version="1.0" encoding="UTF-8"?>
<response>
  <project>
    <ixGroup>105</ixGroup>
    <sGroup>Place Group</sGroup>
  </project>
  <project>
    ...

And I use the following code to extract the distinct <ixGroup> and <sGroup> text values from it:

XDocument doc = XDocument.Load(@"C:\temp\xmlParse2.xml");

var projects = (from project in doc.Descendants("project")
                select new {
                    id = project.Element("ixGroup").Value,
                    name = project.Element("sGroup").Value
                }).Distinct();

foreach(var project in projects)
{
    project.id.Dump("id");
    project.name.Dump("name");
}

If the same xml file had an extra element like the <projects> one added below:

<response>
  <projects>
    <project>
      <ixGroup>105</ixGroup>
      <sGroup>Place Group</sGroup>
    </project>
    <project>
      ...

How would I modify the LINQ code above to still access the <project> elements?


Solution

  • You wouldn't have to. I've just tested it, and your current LINQ statement will still return all the <project> elements regardless of whether they're nested within a <projects> element.