XPath for element whose attribute value ends with

2019-02-23 06:40发布

Given that the HTML contains:

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

How do we write the following expression in XPath:

Find a <div> element whose tagname attribute ends with the string 'Destination'

I've been searching for days and I can't come up with something that works. Among many, I tried for example:

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

4条回答
成全新的幸福
2楼-- · 2019-02-23 07:21

XPath 2 or 3: There's always regex.

.//div[matches(@tagname,".*_Destination$")]
查看更多
时光不老,我们不散
3楼-- · 2019-02-23 07:21

You can use ends-with (Xpath 2.0)

//div[ends-with(@tagname, 'Destination')]
查看更多
狗以群分
4楼-- · 2019-02-23 07:23

You could use the below xpath which will work with Xpath 1.0

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

Basically it checks if there is any string ( or no strings ) before the first occurrence of Destination but there should not be any text after the Destination

Test input :

<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>

Test output:

<div class="panel panel-default"
     tagname="779853cd-355b-4242-8399-dc15f95b3276_Destination"/>
<div class="panel panel-default" tagname="Destination"/>
查看更多
一纸荒年 Trace。
5楼-- · 2019-02-23 07:39

XPath 2.0

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

XPath 1.0

//div[substring(@tagname,string-length(@tagname) -string-length('Destination') +1) 
      = 'Destination']
查看更多
登录 后发表回答