我正在撰寫一個腳本來決議這個 XML。
我想用DOMDocument和DOMXpath<Contents>決議所有節點。但由于某種原因,我嘗試的所有 XPath 查詢都失敗了。
我的代碼:
<?php
$apiUrl = 'https://chromedriver.storage.googleapis.com/?delimiter=/&prefix=98.0.4758.48/';
$xmlContents = file_get_contents($apiUrl);
if (!$xmlDom->loadXML($xmlContents)) {
throw new \Exception('Unable to parse the chromedriver file index API response as XML.');
}
$xpath = new \DOMXPath($xmlDom);
// **I tried several $query values here**
$fileEntries = $xpath->query($query, null, false);
if (!$fileEntries instanceof \DOMNodeList) {
throw new \Exception('Failed to evaulate the xpath into node list.');
}
echo "There are {$fileEntries->length} results\n";
foreach ($fileEntries as $node) {
/** @var \DOMNode $node */
var_dump($node->nodeName);
}
$query我試過的 XPath :
/ListBucketResult/Contents/Contents//Contents
所有這些結果都在“有 0 個結果”中。
如果我*在 $query 中使用,它將列出<ListBucketResult>根節點內的所有節點:
There are 10 results
string(4) "Name"
string(6) "Prefix"
string(6) "Marker"
string(9) "Delimiter"
string(11) "IsTruncated"
string(8) "Contents"
string(8) "Contents"
string(8) "Contents"
string(8) "Contents"
string(8) "Contents"
簡單的方法是過濾具有nodeName屬性的節點。但我確實想知道我的 XPath 查詢出了什么問題。我錯過了什么?
uj5u.com熱心網友回復:
你錯過了——因為你沒有在給定的視圖中看到它——所有節點都在一個命名空間中,因為根元素確實是
<ListBucketResult xmlns="http://doc.s3.amazonaws.com/2006-03-01">
所以這個元素和它的所有子元素都在命名空間中http://doc.s3.amazonaws.com/2006-03-01。像這樣添加命名空間
$xpath->registerNamespace("aws", "http://doc.s3.amazonaws.com/2006-03-01");
之后$xpath = new DOMXPath($xmlDom);并在你的 XPath 運算式中使用它
/aws:ListBucketResult/aws:Contents
應該可以解決您的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414298.html
標籤:
