【问题标题】:Use LINQ to find nodes in xml document where nodes at different levels have same name使用 LINQ 在 xml 文档中查找不同级别的节点具有相同名称的节点
【发布时间】:2013-07-02 10:46:00
【问题描述】:
<category>
   <category>
       <category>
       </category>
   </category>
</category>
<category>
   <category>
       <category>
       </category>
   </category>
</category>

我有一个如上所述的 xml 段,其中许多子节点与父节点具有相同的名称,重复多个层次。使用 LINQ to XML 我想查询 1)只有顶级节点和 2)所有二级节点及其后代。 通常,如果节点名称是唯一的,我可以使用 .Descendents("category") 或 .Element() ,但我找不到在 XML 层次结构中指定级别/深度的任何方法。

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

    1) 只是顶级节点

    Elements 方法只接受当前节点正下方的元素,因此使用它来获取category 元素的顶层:

    var topCategories = source.Elements("category");
    

    2) 所有二级节点及其后代

    结合ElementsDescendants 得到:

    var topCategories = source.Elements("category").Descendants("category");
    

    在这两个示例中,sourceXElement,它是 category 部分的父级。例如。 categories 在以下文档中:

    <root>
        <elements>
            <element />
            <element />
        </elements>
        <categories>
            <category>
                <category>
                    <category>
                        <category />
                    </category>
                </category>
            </category>
            <category>
                <category>
                    <category />
                </category>
            </category>
        </categories>
    </root>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多