如何使用 simpleXML (php) 通过 xpath 获取 parent 节点

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>

我希望 parent 节点(行)具有此 xpath 限制(有效):

$row2 = $xml->xpath("//*[local-name()='row']/@*[local-name()='r' and .= '18']");

现在 returns 我这个 :

array(1) {
  [0]=>
  object(SimpleXMLElement)#383 (1) {
    ["@attributes"]=>
    array(1) {
      ["r"]=>
      string(2) "18"
    }
  }
}

我想要 parent..(行)

我该怎么办?

非常感谢。

先说正事。要摆脱 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() 总是 return 一个数组。这里可能有几个或没有 row 元素。使用条件验证您是否获取了节点或使用循环遍历数组。

本例中的表达式包含两部分://m:row 获取文档中的任何 row 元素节点。 [] 包含找到的节点的过滤条件。在这种情况下 @id=18,属性节点 id 应该等于 18.