thom
thom

Reputation: 21

Dom Xpath issue

I don't get why I can't get nothing with XPath. What's wrong?

<?php
$dom_object = new DOMDocument();
$domxpath_object = new DOMXpath($dom_object);

$dom_object->loadXML('<?xml version="1.0" encoding="UTF-8" ?><databases><foo>bar</foo></databases>');
$domnodelist_object = $domxpath_object->query('/');
echo '<pre>' . print_r($domnodelist_object->item(0)->hasChildNodes(), true) . '</pre>'; // output: nothing

print_r($dom_object->childNodes->item(0)->nodeValue); // output bar
?>

Thank you.

Upvotes: 2

Views: 380

Answers (1)

Orbling
Orbling

Reputation: 20602

[Comment converted to answer, for the benefit of those searching here after.]

DOMXpath seems to establish it's state at the time of creation rather than linking to the DOMDocument it was created from. Updates to the DOMDocument, in this case a ->loadXML() call do not follow through to the DOMXpath object.

It is therefore necessary to load the XML, create the full DOM tree, before instantiating the XPath object.

<?php
$dom_object = new DOMDocument();    
$dom_object->loadXML('<?xml version="1.0" encoding="UTF-8" ?><databases><foo>bar</foo></databases>');

// XPath created from DOMDocument, after loading
$domxpath_object = new DOMXpath($dom_object);

$domnodelist_object = $domxpath_object->query('/');

// ... additional processing

Upvotes: 1

Related Questions