XML xpath,获取父元素直到特定元素

发布于 2024-11-10 07:59:49 字数 580 浏览 5 评论 0原文

我正在寻找正确的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赠意 2024-11-17 07:59:49

给定 XML,

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

您可以使用 XPath 表达式从 baz 找到最近的祖先 foo 元素:

//baz/ancestor::foo[1]

这将选择 id“i2”的 foo 元素节点。

因此,在您的示例中(如果我理解正确)一旦您获得了所需的“a”元素,您就可以通过将“/ancestor::div[1]”附加到您的元素,将树“备份”到最近的祖先div。表达。

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.

扛刀软妹 2024-11-17 07:59:49

使用

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

这会选择作为任何 a 元素子级的任何文本节点,该元素具有值为 '1'< 的 class 属性/code> 并且(a 元素)是任何 div 元素的后代,该元素是名为 root 的顶部元素的子元素。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文