[英]How to get parent node with xpath using simpleXML (php)
我在使用XML文件時遇到問題。
這里是 :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheetPr codeName="Feuil3">
<tabColor rgb="FF00B050"/>
</sheetPr>
<dimension ref="A18"/>
<sheetViews>
<sheetView tabSelected="1" topLeftCell="A3" workbookViewId="0">
<selection activeCell="A3" sqref="A3"/>
</sheetView>
</sheetViews>
<sheetFormatPr baseColWidth="10" defaultRowHeight="15"/>
<cols>
<col min="1" max="1" width="29.140625" bestFit="1" customWidth="1"/>
<col min="2" max="2" width="24.42578125" bestFit="1" customWidth="1"/>
<col min="3" max="3" width="14.28515625" bestFit="1" customWidth="1"/>
<col min="4" max="4" width="5.42578125" bestFit="1" customWidth="1"/>
<col min="5" max="5" width="6.140625" bestFit="1" customWidth="1"/>
</cols>
<sheetData>
<row r="18" ht="16.5" customHeight="1"/>
</sheetData>
<sortState ref="A2:E1036">
<sortCondition descending="1" ref="C1"/>
</sortState>
<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>
</worksheet>
我想要具有此xpath限制的父節點(行)(有效):
$row2 = $xml->xpath("//*[local-name()='row']/@*[local-name()='r' and .= '18']");
現在,它返回給我:
array(1) {
[0]=>
object(SimpleXMLElement)#383 (1) {
["@attributes"]=>
array(1) {
["r"]=>
string(2) "18"
}
}
}
我想要父母..(行)
我應該怎么做 ?
非常感謝。
首先。 要擺脫local-name()
並停止忽略名稱空間,請為其注冊一個前綴。 之后,這只是一個簡單的條件。
$worksheet = new SimpleXMLElement($xml);
$worksheet->registerXpathNamespace(
'm', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'
);
var_dump(
$worksheet->xpath('//m:row[@r=18]')
);
輸出:
array(1) {
[0]=>
object(SimpleXMLElement)#2 (1) {
["@attributes"]=>
array(3) {
["r"]=>
string(2) "18"
["ht"]=>
string(4) "16.5"
["customHeight"]=>
string(1) "1"
}
}
}
SimpleXMLElement::xpath()
將始終返回一個數組。 這里可能是幾個或沒有row
元素。 使用條件來驗證您是否已獲取節點或使用循環遍歷數組。
這種情況下的表達式包含兩部分: //m:row
獲取文檔中的任何row
元素節點。 []
包含找到的節點的過濾條件。 在這種情況下@id=18
,屬性節點id
應該等於18
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.