[英]Get the nodevalue of the immediate node using php domdocument xpath query
[英]Get Xpath parent node with DOMDocument PHP?
我需要在 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]
is (object value omitted)
,为什么? 我会得到
<Id>138</Id>
<Name>Parent Category</Name>`
[parentNode]
is(object value omitted)
,为什么?
这是因为您使用了print_r
函数并且它创建了这样的输出(通过 dom 扩展的内部辅助函数)。 创建此代码的代码行是:
print_r($nodes);
当使用print_r
或var_dump
时,字符串“ (object value omitted)
”由DOMNode给出。 它告诉您,该字段(名为parentNode )的对象值没有显示而是省略了。
从该消息中,您可以得出结论,该字段的值是一个对象。 对类名的简单检查可以验证这一点:
echo get_class($nodes->parentNode), "\n"; # outputs "DOMElement"
将其与整数或(空)字符串的字段进行比较:
[nodeType] => 1
...
[prefix] =>
[localName] => ProdCategory
所以我希望这能让你明白。 只需访问该字段即可获取父节点对象:
$parent = $nodes->parentNode;
并做了。
如果你想知道 PHP 给你的某个字符串,并且你觉得它可能是内部的东西,你可以在http://lxr.php.net/上快速搜索所有 PHP 的代码库, 这里是一个字符串查询示例在你的问题中。
只是把XPath查询节点作为文件系统路径,提到这里
向上移动 2 个节点并获取父节点并从中获取您需要的内容,例如 Id 或 Name。
例子:
<?php
$dom = new DOMDocument();
$dom->load("ProdCategories_small.xml");
$xpath = new DOMXPath($dom);
$parentNode = $xpath->query('//ProdCategory[Id="141"]/../..')->item(0);
$id = $xpath->query('./Id', $parentNode)->item(0);
$name = $xpath->query('./Name',$parentNode)->item(0);
print "Id: " . $id->nodeValue . PHP_EOL;
print "Name: " . $name->nodeValue . PHP_EOL;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.