Home > database >  Wildcards (*) in XPath?
Wildcards (*) in XPath?

Time:08-10

I am trying to find an element from XML string based on an attribute and I have two situations:

//person[contains("name", "aa bb cc")]//phone

or

//person[contains("name", "aa cc")]//phone

I want to find both of these elements, is it possible to use wildcards for this case? I tried:

//person[contains("name", "aa*cc")]//phone 

this doesn't work. Any suggestions?

The XML has this shape, and I want to get all the phone numbers:

<people>
  <person>
    <phone>315255414</phone>
    <name>aa cc</name>
  </person>

  <person>
    <phone>523525</phone>
    <name>aa bb cc</name>
  </person>
</people>

CodePudding user response:

After you updated the question I would suggest the following XPath expression to find the phone numbers:

//person[./*[starts-with(@name,'ab') and ends-with(@name, 'cc')]]/phone

In case name or phone can be a non-direct children of person the expression could be changed to the following:

//person[.//*[starts-with(@name,'ab') and ends-with(@name, 'cc')]]//phone

CodePudding user response:

Glob pattern wildcards (where * matches any characters), are not supported in XPath, but starting with XPath 2.0, full regular expressions (where .* matches zero or more characters) are supported.

XPath 2.0

This XPath,

//person[matches(name, '^aa.*cc$')]/phone

uses XPath 2.0's regular expression facilities to select the phone elements of those person elements whose name child element's string value starts with aa and ends with cc.

XPath 1.0

This XPath,

//person[starts-with(name, 'aa')][ends-with(name, 'cc')]/phone

does the same but only requires XPath 1.0.

  • Related