【问题标题】:Selecting Multiple Nodes on the Same Level w/ LINQ使用 LINQ 在同一级别上选择多个节点
【发布时间】:2014-05-28 09:00:51
【问题描述】:

我正在尝试在一个查询中选择多个节点。

我的 XML 看起来像

<View Id="View#1">
    <Node1 DefinitionId="DefinitionId1">
        // ...
    </Node1>
</View>
<View Id="View#2">
    <Node2 DefinitionId="DefinitionId2">
        // ...
    </Node2>
</View>
<View Id="View#3">
    <Node3 DefinitionId="DefinitionId3">
        // ...
    </Node3>
</View>

我目前正在通过 XDocument.Load 加载 XML 文档,我正在通过 LINQ to XML 解析生成的 XML。

我基本上是在尝试将所有节点类型的所有定义 ID 放入单个字符串集合中。

我当前的代码如下所示

IList<string> node1Ids = _xmlFile
    .Descendants("Node1")
    .Select(n => n.Attribute("DefinitionId").Value).ToList();

IList<string> node2Ids = _xmlFile
    .Descendants("Node2")
    .Select(n => n.Attribute("DefinitionId").Value).ToList();

有没有办法将所有这些都放在一个查询中,例如

IList<string> nodeIds = _xmlFile
    .Descendants("Node1")
    .Descendants("Node2")
    .Descendants("Node3")
    .Select(n => n.Attribute("DefinitionId").Value).ToList();

显然上述方法不起作用,但我想知道是否有等效方法可以让我做同样的事情。

【问题讨论】:

    标签: c# xml linq linq-to-xml


    【解决方案1】:

    你可以试试_xmlFile.Descendants("View").Elements().Attributes("DefinitionId").Select(a =&gt; a.Value).ToList()。这假设您正在寻找所有View 元素的所有子元素的DefinitionId 属性。或者你需要像Descendants().Where(d =&gt; d.Name.LocalName.StartsWith("Node")).Attributes("DefinitionId").Select(a =&gt; a.Value).ToList() 这样的东西。

    【讨论】:

      【解决方案2】:

      你可以试试下面的:

      IList<string> nodeIds = _xmlFile
          .Descendants().Where( d => d.Name.LocalName.StartsWith("Node") )
          .Select(n => n.Attribute("DefinitionId").Value).ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-23
        • 2011-02-18
        • 1970-01-01
        • 2018-10-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        相关资源
        最近更新 更多