XML xpath, get the parent element till a specific element

后端 未结 2 1665
半阙折子戏
半阙折子戏 2021-02-01 15:40

I\'m looking for the right xpath syntax to get a specific parent of an element. Example:

root
   |- div
   |     |
   |     |----??? ---|
   |     |           |-         


        
2条回答
  •  无人及你
    2021-02-01 15:52

    Given the XML

    
    
        
            
                
            
        
    

    You can find the nearest ancestor foo element from baz using the XPath expression:

    //baz/ancestor::foo[1]

    Which will select the foo element node of id "i2".

    So in your example (if I understand right) once you have got the "a" element you want, you can get "back up" the tree to the nearest ancestor div by appending "/ancestor::div[1]" to your expression.

提交回复
热议问题