Using LINQ to XML to match deeper descendant eleme

2019-08-22 14:32发布

问题:

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?

回答1:

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.



回答2:

You don't need to modify your code at all. The Descendants method will search as far down the tree as it needs to in order to find matching elements, which can be both a curse and a blessing. In your case, the code as written will continue to work even if you add an intermediate <projects> node.

(The method that only searches for direct child methods is Children().



回答3:

Elements only searches child nodes, but Descendants goes all the way down the tree. In other words, you won't have to do anything.