XPath testing that string ends with substring?

前端 未结 5 511
一整个雨季
一整个雨季 2021-01-17 17:06

Given that the HTML contains:

  
<
相关标签:
5条回答
  • 2021-01-17 17:16

    You can use ends-with (Xpath 2.0)

    //div[ends-with(@tagname, 'Destination')]
    
    0 讨论(0)
  • 2021-01-17 17:16

    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"/>
    
    0 讨论(0)
  • 2021-01-17 17:26

    XPath 2 or 3: There's always regex.

    .//div[matches(@tagname,".*_Destination$")]
    
    0 讨论(0)
  • 2021-01-17 17:32

    XPath 2.0

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

    XPath 1.0

    //div[substring(@tagname, string-length(@tagname) 
                              - string-length('Destination') + 1)  = 'Destination']
    
    0 讨论(0)
  • 2021-01-17 17:37

    //div[ends-with(@tagname, 'Destination')] might not show in the DOM as a match but will work when running the code.

    0 讨论(0)
提交回复
热议问题