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></databa开发者_如何学Cses>');
$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.
[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
精彩评论