![](/img/trans.png)
[英]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.