关于xml:使用DomDocument PHP获取Xpath父节点吗?

Get Xpath parent node with DomDocument PHP?

我需要在php中获取特定节点的父级。
我正在使用DomDocument和Xpath。
我的xml是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<ProdCategories>
<ProdCategory>

    <Id>138</Id>

    <Name>Parent Category</Name>

    <SubCategories>

        <ProdCategory>

            <Id>141</Id>

            <Name>Category child</Name>

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

php代码:

1
2
3
4
5
$dom = new DOMDocument();
$dom->load("ProdCategories_small.xml");
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//ProdCategory/Id[.="141"]/parent::*')->item(0);
print_r($nodes);

打印为:

1
2
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](object value omitted),为什么? 我会得到

1
2
3
    <Id>138</Id>

    <Name>Parent Category</Name>`


The [parentNode] is (object value omitted), why?

这是因为您使用了print_r函数,并且它创建了这样的输出(通过dom扩展的内部帮助器函数)。创建此代码的代码行是:

1
print_r($nodes);

当在其上使用print_rvar_dump时,DOMNode给出字符串" (object value omitted)"。它告诉您,该字段(名为parentNode)的对象值未显示,但被省略。

根据该消息,您可以得出结论,该字段具有作为对象的值。对类名的简单检查可以验证这一点:

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

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

1
2
3
4
[nodeType] => 1
...
[prefix] =>
[localName] => ProdCategory

因此,我希望这可以为您解决。只需访问该字段即可获取父节点对象:

1
$parent = $nodes->parentNode;

并做了。

如果您想知道PHP可以给您的某个字符串,并且您感觉它可能是内部的,则可以在http://lxr.php.net/上快速搜索PHP的所有代码库,下面是查询字符串的示例在你的问题。


只需将xpath查询节点视为文件系统路径,如此处所述

向上移动2个节点并获取父节点,并从中获取所需的信息,例如ID或Name。

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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;