简体   繁体   English

XPATH表达式选择有两个有孩子的父母

[英]XPATH Expression to Select Parent With Two Children Which Have Children

I have an XML structure similar to this: 我有一个类似于以下的XML结构:

<Header>
    <ElementA>
        <ElementB>
            <ElementC/>
            <ElementC/>
        </ElementB>
        <ElementB/>
    </ElementA>
</Header>

where the <ElementB> may have a sequence of <ElementC> , or may have none. 其中<ElementB>可能具有<ElementC>的序列,也可能没有。

I can select <ElementA> nodes which have two <ElementB> by /Header/ElementA/ElementB/following-sibling::ElementB . 我可以通过/Header/ElementA/ElementB/following-sibling::ElementB选择具有两个<ElementB><ElementA>节点。 I can select <ElementA> nodes which contain an <ElementB> node which contains an <ElementC> using /Header/ElementA/ElementB[ElementC] . 我可以使用/Header/ElementA/ElementB[ElementC]选择包含<ElementB>节点且包含<ElementC> <ElementA>节点。

But how do I select <ElementA> nodes which contain an <ElementB> which contains an <ElementC> followed by another <ElementB> containing another <ElementC> . 但是,如何选择包含<ElementA>节点,其中<ElementB>包含<ElementC>然后是另一个<ElementB>包含另一个<ElementC> Something like this: 像这样:

<Header>
    <ElementA>
        <ElementB>
            <ElementC/>
            <ElementC/>
        </ElementB>
        <ElementB>
            <ElementC/>
            <ElementC/>
        </ElementB>
    </ElementA>
</Header>

Note that you don't have to explicitly search the following-sibling axis. 请注意,您不必显式搜索后继轴。 These two patterns will return the same result: 这两种模式将返回相同的结果:

foo[bar/following-sibling::bar]

and

foo[bar[2]]

So your pattern can be as simple as: 因此,您的模式可以很简单:

/Header/ElementA[ElementB[ElementC][2]]

which will find ElementA elements that have two or more ElementB children, each of which has an ElementC child. 它将找到具有两个或多个ElementB子元素的ElementA元素,每个子ElementC都有一个ElementCElementC

I may just have answered my own question: 我可能只是回答了我自己的问题:

/Header/ElementA[ElementB[ElementC]/following-sibling::ElementB[ElementC]]

seems to work. 似乎有效。 The reason it didn't appear to work before is that my document, all 88,000 lines of it, had no occurrence of that pattern. 之前似乎无法正常运行的原因是我的文档(共88,000行)都没有出现这种模式。 This probably indicates a bug in the code that produces it, not a bug in my XPATH expression. 这可能表示产生该错误的代码中的错误,而不是我的XPATH表达式中的错误。

嵌套谓词可以完成工作:

/Header/ElementA[ElementB[following-sibling::ElementB/ElementC]/ElementC]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM