2

I wrote a Xpath query to look for an element with a nodeValue that contains a string.

/campaigns/campaign[contains("7218322441485795", creative_id)] 

However, the XML I'm querying has multiple <creative_id> elements;

<campaigns>
    <campaign>
        <creative_id>41485795</creative_id>
        <creative_id>41485759</creative_id>
        <creative_id>41485694</creative_id>
        <resources>
        ....

The problem is that the query only evaluates the first creative_id element and not second & third.

How do I write the XPath query to not be limited to the first creative_id element?

John Giotta
  • 16,432
  • 7
  • 52
  • 82
  • How do you call this XPath query? – Chris Dec 14 '11 at 18:58
  • @Chris http://en.wikipedia.org/wiki/XPath – John Giotta Dec 14 '11 at 19:00
  • Do you intend for the arguments to `contains` to be ordered this way? You're currently looking for the value of `creative_id` in that string, not the value of that string in `creative_id`. – Wayne Dec 14 '11 at 19:03
  • @lwburk - Yes, the query string that I'm comparing is actually 16 digits long. It's only the last 8 I care to evaluate. – John Giotta Dec 14 '11 at 19:08
  • You might have a look at this: http://stackoverflow.com/a/3470779/592746 – Wayne Dec 14 '11 at 19:15
  • @lwburk Thanks for that, but I'm using DOMXPath of PHP and it only supports XPath 1.0. Not by choice unfortunately. Baked into the framework. – John Giotta Dec 14 '11 at 19:20
  • Yeah, if you look at Dimitre's answer, he shows how to do an `ends-with` in XPath 1.0. You may not need it, but, then again, you might, if you're concerned about strict matching. – Wayne Dec 14 '11 at 19:26
  • @mellamokb L.O.L. I meant, what code is he using, but of course it is not really applicable as per lwburk's answer. – Chris Dec 14 '11 at 19:58
  • @Chris - I knew what you meant :) – Wayne Dec 14 '11 at 21:22

1 Answers1

3

The XPath contains function returns true when the string value of the second argument is found in the first argument. Your ordering seems suspicious. You're currently looking for the string value of creative_id in the given string, not the value of that string in creative_id.

Assuming that the argument ordering is correct, the following expression returns a campaign element if any of its creative_id children match a portion of the provided string:

/campaigns/campaign[creative_id[contains("7218322441485795", .)]]
Wayne
  • 59,728
  • 15
  • 131
  • 126