Pavel Straka
Pavel Straka

Reputation: 427

XPath get node by value

I have this XML:

<root>
  <experiment accessCount="1" downloadCount="1">alfa</experiment>
  <experiment accessCount="1" downloadCount="1">beta</experiment>
</root>

And I would like to detect if the node experiment with value alfa exists. But this PHP code is returning to me all values.

    $this->xml = simplexml_load_file("data/stats.xml") or die("Error: Cannot create object");
    $node = $this->xml->xpath("/root[experiment='alfa']");

Where am I wrong?

Upvotes: 5

Views: 4705

Answers (3)

Yogib
Yogib

Reputation: 55

Please try this code

/root/experiment[matches(.,'alfa')]

will work absolutely

Upvotes: -1

kjhughes
kjhughes

Reputation: 111726

Your XPath,

    /root[experiment='alfa']

says:

Select the root element that contains an experiment element with string value equal to 'alfa'.

There is one such root element in your example, and it contains both experimental elements.


This XPath,

    /root/experiment[.='alfa']

says:

Select the experiment element with string value equal to 'alfa'.

And will select the one experiment element you seek.

Upvotes: 6

code-kobold
code-kobold

Reputation: 824

You can query the node value with text():

$node = $this->xml->xpath("/root/experiment[text()='alfa']");

Upvotes: 1

Related Questions