开发者

Dom Xpath issue

开发者 https://www.devze.com 2023-02-08 10:45 出处:网络
I don\'t get why I can\'t get nothing with XPath. What\'s wrong? <?php $dom_object = new DOMDocument();

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
0

精彩评论

暂无评论...
验证码 换一张
取 消