XPath 测试该字符串以子字符串结尾?

XPath testing that string ends with substring?

假设 HTML 包含:

  <div tagname="779853cd-355b-4242-8399-dc15f95b3276_Destination" class="panel panel-default"></div>

我们如何在 XPath 中编写以下表达式:

找到一个 <div> 元素,其 tagname 属性以字符串 'Destination'

我已经搜索了好几天了,但我找不到有用的东西。其中,我试过例如:

div[contains(@tagname, 'Destination')]

您可以使用 ends-with (Xpath 2.0)

//div[ends-with(@tagname, 'Destination')]

您可以使用下面的 xpath,它适用于 Xpath 1.0

//div[string-length(substring-before(@tagname, 'Destination')) >= 0 and string-length(substring-after(@tagname, 'Destination')) = 0 and contains(@tagname, 'Destination')]

基本上它会检查在第一次出现 Destination 之前是否有任何字符串(或没有字符串),但在 Destination

之后不应该有任何文本

测试输入:

<root>
<!--Ends with Destination-->
<div tagname="779853cd-355b-4242-8399-dc15f95b3276_Destination" class="panel panel-default"></div>
<!--just Destination-->
<div tagname="Destination" class="panel panel-default"></div>
<!--Contains Destination-->
<div tagname="779853cd-355b-4242-8399-dc15f95b3276_Destination_some_text" class="panel panel-default"></div>
<!--Doesn't contain destination-->
<div tagname="779853cd-355b-4242-8399-dc15f95b3276" class="panel panel-default"></div>
</root>

测试输出:

<div class="panel panel-default"
     tagname="779853cd-355b-4242-8399-dc15f95b3276_Destination"/>
<div class="panel panel-default" tagname="Destination"/>

XPath 2.0

//div[ends-with(@tagname, 'Destination')]

XPath 1.0

//div[substring(@tagname, string-length(@tagname) 
                          - string-length('Destination') + 1)  = 'Destination']

XPath 2 或 3:总是有正则表达式。

.//div[matches(@tagname,".*_Destination$")]