21

Is it possible to have XPath expression with multiple contains of different element values?

XML

<data>
   <person>
      <firstname>Kerry</firstname>
      <lastname>Packer</lastname>
      <address>Crown</address>
   <person>
   <person>
      <firstname>Kerry</firstname>
      <lastname>Murdoch</lastname>
      <address>California</address>
   <person>
<data>

PHP

$xml = simplexml_load_string($data);
$elements = $xml->xpath("(//person)[firstname[contains(., 'Kerr')]] and [lastname[contains(., 'och')]]");

Currently above XPath expression is flagged as invalid. However if I use it with one element,

$xml->xpath("(//person)[firstname[contains(., 'Kerr')]]"); 

then it works fine.

1 Answer 1

41

You simply want

//person[contains(firstname, 'Kerr') and contains(lastname, 'och')]
1
  • 2
    We can also use an "or" clause in the search. Nov 6, 2015 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.