开发者

Get elements of specific hierarchy level

Is there any way to retrieve all elements of specific hierarchy level using XPath?

Upd.

<A>
开发者_C百科   <B>1</B>
   <B>2</B>
</A>
<C>
   <D>3</D>
   <D>4</D>
</C>

I need to retrieve all B and D elements (hierarchy level = 2)


Your example lacks a root element, so I assume something like this:

<ROOT>
  <A>
    <B>1</B>
    <B>2</B>
  </A>
  <C>
    <D>3</D>
    <D>4</D>
  </C>
</ROOT>

With this, a simple version would be to just use the appropriate number of 'any element' wildcards to get your result:

xpath = '/*/*/*'

(Meaning 'select any child element of any child element of any root element')

Alternatively, if you want to express the level numerically, you could use:

xpath = '//*[count(ancestor::*) = 2]'

(Meaning 'select any element with 2 ancestors')


Edit/Note: As Dimitre Novatchev correctly pointed out, it is important to differentiate between nodes and elements, and I fixed my answer accordingly. (While elements are nodes themselves, there are also six other types of nodes!)

The difference can be illustrated with the given example by altering the ancestor based xpath slightly to:

xpath = '//*[count(ancestor::node())=2]'

This would select A and B, as the root element would count as one ancestor node, and the root node '/' as another!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜