xpath - Looking for n-th instance of x node in root node -
suppose have following xml
<root> <x> <y /> <z> <y /> </z> <n> <m> <y />* </m> </n> </x> <x> <y /> <z> <y /> </z> <y />* </x> </root>
i retrieve y nodes followed *
so third node in x ancestor node
i tried like:
//x//y[3]
however doesn't work guess work if y nodes on same level.
so tried (//x//y)[3]
retrieves 1 node (third one) in whole document
so tried like:
//x(//y)[3] //x(//y[3]) //x//(y[3])
etc. parse error
is there way retrieve need using xpath?
use:
//x/descendant::y[3]
this selects every third y
descendant of each x
in document. helps write out expanded expression see what's going on. in case, following:
//x//y[3]
is equivalent to:
/descendant-or-self::node()/child::x/descendant-or-self::node()/child::y[3]
written way becomes obvious why doesn't wanted (i.e. it's looking y
third child of x
element , there isn't one). wanted every third y
descendant. here expanded:
/descendant-or-self::node()/child::x/descendant::y[3]
the important lesson here pays know xpath abbreviated syntax doing. spec quite readable. recommend taking look.
Comments
Post a Comment