Get elements of specific hierarchy level

前端 未结 1 611
无人共我
无人共我 2021-01-22 11:37

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

Upd.


   1
   2


        
相关标签:
1条回答
  • 2021-01-22 11:55

    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 讨论(0)
提交回复
热议问题