Home > Enterprise >  XPath for id attribute with changing substring in middle?
XPath for id attribute with changing substring in middle?

Time:10-11

I have a website I need to isolate XPATH identifiers on - they have an XPath ID like this //*[@id="panel-detail-6163748c7952a-partnerCode"]

The issue is that the website changes the value 6163748c7952a on every page load.

Is there any such XPath expression which can match on the first/last part of that string? So of a wildcard like //*[@id="panel-detail-*-partnerCode"]

CodePudding user response:

This XPath 2.0 expression,

//*[matches(@id, "^panel-detail-.*-partnerCode$")]

or this XPath 1.0 expression,

//*[starts-with(@id, 'panel-detail-') and
    substring(@id, string-length(@id) - string-length('-partnerCode')   1)  
                                                    = '-partnerCode']

will match all elements whose id attribute value starts and ends with the noted substrings.

See also

CodePudding user response:

There are few methods in xpath such as starts-with or ends-with. Many time folks replaces them with contains which should be discourage.

Please note that ends-with is available with xpath v2.0 .

xpath v1.0 :

//*[starts-with(@id,'panel-detail-') and contains(@id, '-partnerCode')]

xpath v2.0 :

//*[starts-with(@id,'panel-detail-') and ends-with(@id, '-partnerCode')]
  • Related