使用LINQ to XML来匹配更深的后代元素? [英] Using LINQ to XML to match deeper descendant elements?

查看:77
本文介绍了使用LINQ to XML来匹配更深的后代元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下XML文件:

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

然后我使用以下代码从中提取不同的<ixGroup><sGroup>文本值:

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

如果同一个xml文件中有一个额外的元素,例如<projects>,则在下面添加一个元素:

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

如何修改上面的LINQ代码以仍然访问<project>元素?

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

推荐答案

您不必这样做.我已经对其进行了测试,并且您当前的LINQ语句仍将返回所有<project>元素,无论它们是否嵌套在<projects>元素中.

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.

这篇关于使用LINQ to XML来匹配更深的后代元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆