xpath->query() 仅适用于星号



下面是我目前正在使用的代码。

输入 XML 文件可在此处获得:http://pastebin.com/hcQhPSjs

header("Content-Type: text/plain");
  $xmlFile = new domdocument();
  $xmlFile->preserveWhiteSpace = false;
  $xmlFile->load("file:///srv/http/nginx/html/xml/UNSD_Quest_Sample.xml");
  $xpath = new domxpath($xmlFile);
  $hier = '//Workbook';
  $result = $xpath->query($hier);
  foreach ($result as $element) {
    print $element->nodeValue;
    print "n";
  };

现在对于 $hier 变量,PHP 不会解析结果,除非我使用通配符*到达我需要的节点。因此,我没有使用通常的/Workbook/Worksheet/Table/Row/Cell/Data方法来访问节点,而是降级为/*/*[6]/*[2]/* 输入文件是导出为 xml 的 Excel 电子表格。似乎问题可能出在从 xls 导出到 xml 的过程中。

我觉得奇怪的是,Firefox(默认浏览器)不会解析根元素<Workbook>的命名空间属性,而 Chromium 和/或任何文本编辑器会解析
。火狐:

<?mso-application progid="Excel.Sheet"?>
<Workbook>
<DocumentProperties>
<Author>Htike Htike Kyaw Soe</Author>
<Created>2014-01-14T20:37:41Z</Created>
<LastSaved>2014-12-04T10:05:11Z</LastSaved>
<Version>14.00</Version>
</DocumentProperties>
<OfficeDocumentSettings>
<AllowPNG/>
</OfficeDocumentSettings>

铬:

<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Author>Htike Htike Kyaw Soe</Author>
<Created>2014-01-14T20:37:41Z</Created>
<LastSaved>2014-12-04T10:05:11Z</LastSaved>
<Version>14.00</Version>
</DocumentProperties>
<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">
<AllowPNG/>
</OfficeDocumentSettings>  

谁能解释为什么会这样?

您需要为 XML 中使用的命名空间注册并使用命名空间前缀。从标签和元素名称中,我希望它是urn:schemas-microsoft-com:office:spreadsheet - Excel 电子表格。所以这里有一个例子:

$xml = <<<'XML'
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet">
  <Worksheet>
    <Table>
      <Row>
        <Cell>
          <Data>TEST</Data>
        </Cell>
      </Row>
    </Table>
  </Worksheet>
</Workbook>
XML;
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadXML($xml);
$xpath = new DOMXpath($dom);
$xpath->registerNamespace('s', 'urn:schemas-microsoft-com:office:spreadsheet');
$expression = '/s:Workbook/s:Worksheet/s:Table/s:Row/s:Cell/s:Data';
$result = $xpath->evaluate($expression);
foreach ($result as $element) {
  print $element->nodeValue;
  print "n";
}

输出:

TEST

您不应该使用DOMXpath::query(),而应该使用DOMXpath::evaluate()。它还允许您使用 XPath 获取标量值。

$expression = 'string(/s:Workbook/s:Worksheet/s:Table/s:Row/s:Cell/s:Data)';
echo $xpath->evaluate($expression);

相关内容

最新更新