【问题标题】:How to get parent node with xpath using simpleXML (php)如何使用simpleXML(php)通过xpath获取父节点
【发布时间】:2017-02-23 15:53:35
【问题描述】:

我的 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"
    }
  }
}

我想要父母..(行)

我该怎么办?

非常感谢。

【问题讨论】:

  • @Andersson 不,它不起作用.. :(
  • 您正在选择属性。我猜你将不得不使用“and”来过滤属性值。
  • 这不起作用://*[local-name()='row' and 'r' = '18']
  • 我的意思更像是“/sheetData/row[@r='18']”
  • @Fildor,我的命名空间有问题.. 所以它返回空

标签: php xpath simplexml ancestor


【解决方案1】:

先做事。要摆脱 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    相关资源
    最近更新 更多