Combine XPATH predicate with position

后端 未结 3 1977
醉梦人生
醉梦人生 2020-12-30 12:55

I have a collection of div elements that have the class media-gallery-item.
I would like to select element number x.

When just selecting all items,

相关标签:
3条回答
  • 2020-12-30 13:35

    Turns out: parenthesis!

    (//div[@id='content-area']//div[@class='media-gallery-item'])[2] 
    

    works

    0 讨论(0)
  • 2020-12-30 13:43

    It looks like your accessing attributes in the wrong way. Try to use

    /div[@id='content-area' and @class='media-gallery-item'][2]
    
    0 讨论(0)
  • 2020-12-30 13:45

    Step-by-step answer.

    To select elements with a div[@id='content-area'] ancestor, which are the second children of their respective parents use:

    //div[@id='content-area']//div[2]
    

    To select second (in document order) div element with a div[@id='content-area'] ancestor use:

    (//div[@id='content-area']//div)[2]
    

    Do note the difference.

    Then, to select elements, which are second children of their respective parents, providing they have a class 'media-gallery-item' use:

    //div[@id='content-area']//div[2][@class='media-gallery-item']
    

    To select elements, which are the second from those children (of their respective parents) that have a class media-gallery-item:

    //div[@id='content-area']//div[@class='media-gallery-item'][2]
    

    To select second (in document order) div element with a div[@id='content-area'] ancestor, providing it has media-gallery-item class:

    (//div[@id='content-area']//div)[2][@class='media-gallery-item']
    

    To select second (in document order) from all div element with a div[@id='content-area'] ancestor and a media-gallery-item class:

    (//div[@id='content-area']//div)[@class='media-gallery-item'][2]
    

    Spec quotes as suggested by @Alejandro:

    A predicate filters a node-set with respect to an axis to produce a new node-set. For each node in the node-set to be filtered, the PredicateExpr is evaluated with that node as the context node, with the number of nodes in the node-set as the context size, and with the proximity position of the node in the node-set with respect to the axis as the context position

    http://w3.org/TR/xpath/#predicates

    The proximity position of a member of a node-set with respect to an axis is defined to be the position of the node in the node-set ordered in document order if the axis is a forward axis and ordered in reverse document order if the axis is a reverse axis

    http://w3.org/TR/xpath/#dt-proximity-position

    Bottom line is that the position predicate works with respect to the axis. And you need parenthesis to explicitly declare the priority. Thus not the child axis, but the node-set after resolving descendant-or-self axis will be considered, when calculating position.

    0 讨论(0)
提交回复
热议问题