【问题标题】:XPath: select text after certain tag and before same next tagXPath:在某个标记之后和下一个相同标记之前选择文本
【发布时间】:2011-09-19 08:38:39
【问题描述】:

我有这样的html代码:

<strong>Term:</strong>
Some text<br />
More text<br />
Some more lines of text
<strong>Term:</strong>
Some text<br />
More text<br />
Some more lines of text
<strong>Second term:</strong>
Some text<br />
More text<br />
Some more lines of text
<strong>Term:</strong>
Some text<br />
More text<br />
Some more lines of text

我需要在带有文本“Term”的标签之间和下一个标签之前获取文本节点:

Some text
More text
Some more lines of text
Some text
More text
Some more lines of text
Some text
More text
Some more lines of text

这里可以使用条件:前一个标签必须包含文本“Term”,但我不知道如何创建这样的xpath选择器。

【问题讨论】:

  • 你好,我感觉问题不是很清楚。您能否发布所需的输出。可能到时候我就能明白你到底想要什么。
  • 我更新了这个问题。对不起我的英语不好。
  • 您已更改输入,请同时更新所需的输出。此外,添加有意义的文本以区分儿童 ndoes。根据您的描述,仍然很难理解您需要什么。
  • 我已经扩展了我的答案,即使您仍然怀疑您的需求。看看你是否可以。

标签: xpath


【解决方案1】:
//text()[preceding::*[contains(text(),'Term:')] and following::*[contains(text(),'Term:')]]

这与 empo 所建议的相同。但是我正在寻找一个包含 Term 的节点并返回它们之间存在的所有文本节点。

但是,只有当您没有任何其他“术语”集时,这才有效。 如果是这种情况,请告诉我,因为这样 Xpath 也会返回一些不需要的值。

从现在开始,您已经更新了输入。 我只是在之前的 Xpath 中增加了一个条件。

//text()[preceding::*[contains(text(),'Term:')] and following::*[contains(text(),'Term:')] and not(contains(., 'Term:'))]

@empo 解决方案也有效。但是我们正在考虑&lt;strong&gt;。我编写的 xpath 只是检查单词 'Term:' 并给出它们之间的所有 textNodes。

让我知道这是否适合你。

问候。

【讨论】:

  • 您的解决方案效果很好,但只返回一个匹配项。如果我需要在所有带有文本“Term”的标签之后获取所有文本怎么办?
  • @Stephan 您应该向我们展示更多您的输入文档。
【解决方案2】:

您的问题仍然模棱两可,您的输入文档格式不正确。检查这个:

root/text()[preceding::strong[1][contains(text(),'Term')]]

适用于:

<root>
<strong>Term:</strong>
Some text<br />
More text<br />
Some more lines of text
<strong>Term:</strong>
Some text2<br />
More text2<br />
Some more lines of text2
<strong>Second term:</strong>
Some text3<br />
More text3<br />
Some more lines of text3
<strong>Term:</strong>
Some text4<br />
More text4<br />
Some more lines of text4
</root>

产生:

Some text
More text
Some more lines of text

Some text2
More text2
Some more lines of text2

Some text4
More text4
Some more lines of text4

此 XPath 选择包含字符串 Term: 的元素和包含任何字符串的元素之间的所有文本节点:

//text()[preceding::*[contains(text(),'Term:')] and following::*[text()]]

适用于:

<root>
<strong>Term:</strong>
Some text<br />
More text<br />
Some more lines of text
<strong>Second term:</strong>
Some text2<br />
More text2<br />
Some more lines of text2
</root>

返回:

Some text
More text
Some more lines of text

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多