I have two similar nodes in an XML file. When using a CONTAINS query via XPATH, the XPATH query returns two sets of data. I would like it to only return the exact match. Any idea if this is possible?

Here is my code:

$uc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$lc = "abcdefghijklmnopqrstuvwxyz" ;
$lats = $users->xpath("/users/user[contains(translate(ID, '$uc', '$lc'), translate('$test', '$uc', '$lc'))]/lat");
$lons = $users->xpath("/users/user[contains(translate(ID, '$uc', '$lc') ,translate('$test', '$uc', '$lc'))]/lon");

Where $test = "NY:3036N-B"

XML file contains NY:3036N-B and NY:3036N-B2

Thanks in advance,

M

Recommended Answers

All 6 Replies

Thanks...I gave it a try, but get this error:

Invalid expression

Old code:

$lats = $users->xpath("/users/user[contains(translate(ID, '$uc', '$lc'), translate('$test', '$uc', '$lc'))]/lat");

is now:

$lats = $users->xpath('/users/user[text(@ID==$test)]/lat');

Perhaps my syntax is incorrect?

Thanks,

M

Try:

$lats = $users->xpath('/users/user[text()=='$test']/lat');

or:

$lats = $users->xpath('/users/user[@ID=='$test']/lat');

Depends on the XML, which you didn't show.

Here is a snippet of the XML:

<users>
    <user>
        <ID>NY:3036N-B</ID>
        <lat>10</lat>
        <lon>20</lon>
    </user>
<users>  

I tried both examples. If I keep the code the same, I get this message:

Parse error: syntax error, unexpected '$test' (T_VARIABLE)

If I change the code (add double quotes), I get this error:

SimpleXMLElement::xpath(): Invalid expression

Any ideas?

Thanks,

Mark

Oh right, my bad, wrong quotes. I think it should be:

$lats = $users->xpath("/users/user[ID[text()='$test']]/lat");

or:

$lats = $users->xpath("/users/user/lat[../ID/text()='$test']");

$lats = $users->xpath("/users/user[ID[text()='$test']]/lat");

Works like a charm. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.