使用DomDocument PHP获取Xpath父节点?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了使用DomDocument PHP获取Xpath父节点?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在PHP获取特定节点的父节点.
我正在使用DomDocument和xpath.
我的XMl是这样的:
<PRodCategories>
<ProdCategory>

    <Id>138</Id>

    <Name>Parent Category</Name>

    <SubCategories>

        <ProdCategory>

            <Id>141</Id>

            <Name>Category child</Name>

        </ProdCategory>
   </SubCategories>
</ProdCategory>
</ProdCategories>

PHP代码

$dom = new DOMDocument();
$dom->load("ProdCategories_small.xML");
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//ProdCategory/Id[.="141"]/parent::*')->ITem(0);
print_r($nodes);

印刷品是:

DOMElement Object ( 
[tagName] => ProdCategory [schemaTyPEInfo] => [nodeName] => ProdCategory [nodeValue] => 141 Category child [nodeType] => 1 [parentNode] => (object value omitted) [childNodes] => (object value omitted) [FirstChild] => (object value omitted) [lastChild] => (object value omitted) [prevIoUsSibling] => (object value omitted)

[parentNode]是(对象值省略),为什么?我会的

<Id>138</Id>

    <Name>Parent Category</Name>`

这是因为您使用print_r function并创建了这样的输出(via an internal helper function of the dom extension).创建此代码代码行是:

print_r($nodes);

当DOMNode使用print_r或var_dump时,字符串“(对象值省略)”由DOMNode给出.它告诉您,该字段的对象值(名为parentNode)不会显示但会被省略.

从该消息可以得出结论,该字段具有作为对象的值.对类名进行简单检查可以验证:

echo get_class($nodes->parentNode),"\n"; # outputs  "DOMElement"

将其与整数或(空)字符串的字段进行比较:

[nodeType] => 1
...
[prefix] => 
[localName] => ProdCategory

所以我希望这能为你解决这个问题.只需访问该字段即可获取父节点对象:

$parent = $nodes->parentNode;

并做了.

如果你想知道PHP给你的某个字符串,你感觉它可能是内部的,你可以在http://lxr.php.net/,here is an example query for the string in your question快速搜索所有PHP代码库.

脚本宝典总结

以上是脚本宝典为你收集整理的使用DomDocument PHP获取Xpath父节点?全部内容,希望文章能够帮你解决使用DomDocument PHP获取Xpath父节点?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。