【问题标题】:xpath with namespace带有命名空间的 xpath
【发布时间】:2012-03-22 17:45:14
【问题描述】:

我正在尝试将 php SimpleXML 中的 xpath 与 xml 文件一起使用,以下是相关片段:-

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
- <!--  Created on 21-Mar-2012 10:30:46 
  --> 
- <message:Structure xmlns="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/structure" xmlns:message="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message" xsi:schemaLocation="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/structure http://www.sdmx.org/docs/2_0/SDMXStructure.xsd http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message http://www.sdmx.org/docs/2_0/SDMXMessage.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <Header xmlns="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message">
  <ID>none</ID> 
  <Test>false</Test> 
  <Truncated>false</Truncated> 
  <Prepared>2011-11-18T13:56:45</Prepared> 
- <Sender id="OECD">
  <Name xml:lang="en">Organisation for Economic Co-operation and Development</Name> 
  <Name xml:lang="fr">Organisation de coopération et de développement économiques</Name> 
  </Sender>
  </Header>
- <message:CodeLists>
- <CodeList id="CL_MEI_OBS_STATUS" agencyID="OECD">
  <Name xml:lang="en">Observation Status</Name> 
  <Name xml:lang="fr">Statut d'observation</Name> 
- <Code value="B">
  <Description xml:lang="en">Break</Description> 
  <Description xml:lang="fr">Rupture</Description> 
  </Code>
etc. etc.

在我的 php 代码中,我有以下内容,它注册命名空间,然后使用 xpath 获取 CodeLists:- $xml->registerXPathNamespace('test','http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message');

$codelistspath = $xml->xpath('test:CodeLists');

我希望能够使用 xpath 在树中降低一层,即到 CodeList,并认为以下方法可行:-

$codelistpath = $xml->xpath('test:CodeLists/CodeList');

但它只会产生一个空数组。我找不到使用 xpath 访问文档中其他任何内容的方法。我花了几个小时试图解决这个问题,所以任何帮助将不胜感激。

【问题讨论】:

    标签: php xml xpath


    【解决方案1】:

    CodeList 元素属于 默认命名空间,该命名空间继承自 &lt;message:Structure&gt; 元素 - URI 为 http://www.SDMX.org/resources/SDMXML/schemas/v2_0/structure 的命名空间。

    您还需要使用registerXPathNamespace() 进行注册。

    $xml->registerXPathNamespace('default', 'http://www.SDMX.org/resources/SDMXML/schemas/v2_0/structure');
    $codelistpath = $xml->xpath('test:CodeLists/default:CodeList');
    

    【讨论】:

    • 这完全正确,我没有意识到 CodeList 在不同的命名空间中。我已经按照您的建议更改了我的代码,现在一切正常。我感激不尽。
    【解决方案2】:

    看起来 registerXPathNamespace 仅适用于 next xpath 查询(根据 documentation)...所以如果您已经运行 $xml-&gt;xpath('test:CodeLists'),请在运行前再次尝试注册命名空间$xml-&gt;xpath('test:CodeLists/CodeList').

    【讨论】:

    • next 真正的意思是followingxpath() 方法可以在注册后随时使用注册的命名空间调用。
    • 感谢您抽出宝贵时间回复,杰森。正如 Salathe 所说,问题在于 CodeList 位于默认命名空间而不是测试命名空间中。
    • 很公平。有时,当我对这些工具不太熟悉时,我只是扔掉一些东西,看看有什么效果。
    猜你喜欢
    • 2011-01-05
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    相关资源
    最近更新 更多