Using LINQ to XML to match deeper descendant elements?

为君一笑 提交于 2019-12-11 23:19:41

问题


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.



来源:https://stackoverflow.com/questions/5664244/using-linq-to-xml-to-match-deeper-descendant-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!