XML xpath,获取父元素直到特定元素
我正在寻找正确的 xpath 语法来获取元素的特定父元素。 示例:
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]
我想要获取文本“THE TEXT”,但该文本在同一 div 内包含 a [class=1]
。像这样的东西:
//div//a[@class=1]/text[contains(.,'A TEXT')]/parent::*/parent::*.... <till div element> /text
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
给定 XML,
您可以使用 XPath 表达式从 baz 找到最近的祖先 foo 元素:
这将选择 id“i2”的 foo 元素节点。
因此,在您的示例中(如果我理解正确)一旦您获得了所需的“a”元素,您就可以通过将“/ancestor::div[1]”附加到您的元素,将树“备份”到最近的祖先div。表达。
Given the XML
You can find the nearest ancestor foo element from baz using the XPath expression:
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.
使用:
这会选择作为任何
a
元素子级的任何文本节点,该元素具有值为'1'< 的
class
属性/code> 并且(a
元素)是任何div
元素的后代,该元素是名为root
的顶部元素的子元素。Use:
This selects any text node that is a child of any
a
element that has aclass
attribute with value'1'
and that (thea
element) is a descendent of anydiv
element that is a child of the top element namedroot
.