【问题标题】:xpath query omit results with parent tagxpath 查询省略带有父标签的结果
【发布时间】:2018-01-09 11:13:10
【问题描述】:

我对 xpath 相当陌生,因此寻求一些帮助以匹配以下模式。我目前的尝试与我的预期不符。

//text()[1][contains(.,'wordToMatch') and not(self::a)]

我相信你可以从上面的模式中看出,我是个菜鸟。

有效载荷示例 1:

<p>Sample 1 <a href="shouldNotMatchWrappedInA">wordToMatch</a> some 
random text 
to not be matched followed by wordToMatch, this should work.</p>

预期结果1:

wordToMatch (Not the one inside of a' tags but the following one)

有效载荷示例 2:

<p>Sample 2 <a href="shouldNotMatchWrappedInA">wordToMatch</a> some 
random text to not be matched followed by <b>wordToMatch</b> this
should work.</p>

预期结果 2:

wordToMatch (The one inside of the b' tags)

有效载荷示例 3:

<p>Sample 3 <a href="shouldNotMatchWrappedInA">wordToMatch</a> some 
random text to not be matched followed by wordToMatch followed by
further occurrences of wordToMatch which should not be matched.</p>

预期结果 3:

wordToMatch (The second occurrence of the term)

所有 3 个有效负载的预期结果是第一次出现术语 wordToMatch,它NOT 包裹在“a”标签内。

将实现此模式的最终语言是 Java。

请帮忙。

【问题讨论】:

    标签: xpath xpath-2.0 domxpath


    【解决方案1】:

    我认为,从问题中仍然不清楚您究竟在追求什么,为每个样本添加 exact 预期输出将解决问题。无论如何,根据当前信息,考虑以下 XPath,它将匹配内部文本完全等于 'wordToMatch' 的任何元素,并且元素本身不是 &lt;a&gt; 元素:

    //*[.='wordToMatch'][not(self::a)]
    

    这将在第二种情况下返回 b 元素,而在其他情况下则不返回。如果你想放松匹配返回文本节点(而不是父元素),这样做:

    //*[not(self::a)]/text()[contains(.,'wordToMatch')]
    

    更新

    在 XPath 2.0 或更高版本中,您可以使用 for 构造:

    for $t in //*[not(self::a)]/text()[contains(.,'wordToMatch')]
    return 'wordToMatch'
    

    xpatheval demo

    【讨论】:

    • 感谢您的建议,我已采纳并更新了问题。
    • @CoDemystifiedJavaFx 回复很晚,抱歉。根据更新后的问题,我认为 XPath 1.0 可以做的最好的事情是返回相关的文本节点,即包含“wordToMatch”的那个(所以,这个问题中的第二个 XPath,如果你最后可能有额外的[1]只想从每个父元素返回第一个匹配的节点)。然后您可以在 Java 中对 XPath 输出进行后处理,即为每个文本节点返回字符串“wordToMatch”
    • @CoDemystifiedJavaFx 如果您可以使用 XPath 2.0 或更高版本,那么您可能想尝试更新的答案
    猜你喜欢
    • 2015-02-07
    • 2020-08-23
    • 2020-03-13
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    相关资源
    最近更新 更多