XPATH Expression to Select Parent With Two Children Which Have Children
I have an XML structure similar to this:
<Header>
<ElementA>
<ElementB>
<ElementC/>
<ElementC/>
</ElementB>
<ElementB/>
</ElementA>
</Header>
where the <ElementB>
may have a sequence of <ElementC>
, or may have none.
I can select <ElementA>
nodes which have two <ElementB>
by /Header/ElementA/ElementB/following-sibling::ElementB
. I can select <ElementA>
nodes which contain an <ElementB>
node which contains an <ElementC>
using /Header/ElementA/ElementB[ElementC]
.
But how do I select <ElementA>
nodes which contain an <ElementB>
which contains an <ElementC>
followed by another <ElementB>
containing another <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.
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. This probably indicates a bug in the code that produces it, not a bug in my XPATH expression.
A nested predicate gets the job done:
/Header/ElementA[ElementB[following-sibling::ElementB/ElementC]/ElementC]
精彩评论