XPath to find nearest ancestor element that contains an element that has an attribute with a certain value

前端 未结 4 929
轻奢々
轻奢々 2020-12-28 14:31

ancestor::foo[bar[@attr=\"val\"]]

I thought this would work, but it\'s not. I need to find the nearest foo element going up in the tree tha

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 14:43

    Updated to reflect a solution intended by OP.

    See @David's answer

    For a sample xml below,

    
    
        
        
            
        
        
            
                1
                
                    3
                
            
        
    
    

    a valid xpath on the reverse axis with as the context node, a valid solution is

    ./ancestor::foo[bar[@attr='val']][position() = 1]
    

    "./" is optional. position() = 1 is not optional as otherwise the ancestor foo satisfying the predicates would also be returned.

    Old answer:ignore

    This is an old question. but anybody who is interested, the following should get you what the original question intended.

    Reverse axis

    //bar[@attr='val']/ancestor::*[position()=1]
    

    Forward axis

    //*[child::bar[@attr='val']]
    

提交回复
热议问题