XML xpath, get the parent element till a specific element

左心房为你撑大大i 提交于 2019-12-04 08:01:52

问题


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

root
   |- div
   |     |
   |     |----??? ---|
   |     |           |-a [class=1]
   |     |                      |- text[ A TEXT I DON'T WANT]
   |     |
   |     |
   |     |
   |     |-text[THE TEXT]
   |
   |-div 
   |    |-text[THE TEXT I DON'T WANT]
   |
   |-div 
   |    |-text[THE TEXT I DON'T WANT]

I want to get the text "THE TEXT" but the one that contains a [class=1] inside the same div. Something like this:

//div//a[@class=1]/text[contains(.,'A TEXT')]/parent::*/parent::*.... <till div element>  /text

回答1:


Given the XML

<?xml version="1.0"?>
<root>
    <foo id="id1">
        <foo id="i2">
            <baz/>
        </foo>
    </foo>
</root>

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.




回答2:


Use:

/root/div[.//a[@class='1']]/text()

This selects any text node that is a child of any a element that has a class attribute with value '1' and that (the a element) is a descendent of any div element that is a child of the top element named root.



来源:https://stackoverflow.com/questions/6167504/xml-xpath-get-the-parent-element-till-a-specific-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!