2012-03-22 103 views
2

我試圖使用PHP的SimpleXML的XPath與XML文件,以下是相關片段: -的XPath命名空間

<?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去低一個級別的樹,即代碼表和思考以下將工作: -

$ codelistpath = $ XML的>的XPath(「測試:編碼表/代碼表');

但它只是產生一個空的數組。我找不到用xpath訪問文檔中其他任何東西的方法。我花了數小時試圖解決這個問題,所以任何幫助將不勝感激。

回答

2

CodeList元素屬於默認命名空間繼承自<message:Structure>元素 - 其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'); 
+0

這是絕對正確的,我沒有意識到CodeList是在不同的命名空間。按照您的建議,我已經更改了我的代碼,現在所有工作都正在進行。我不知道該怎麼感謝你才足夠。 – fbc 2012-03-22 21:22:00

0

它看起來像registerXPathNamespace僅適用於該下一個 XPath查詢(根據documentation)...因此,如果您已經運行$xml->xpath('test:CodeLists')已經嘗試運行$xml->xpath('test:CodeLists/CodeList')之前重新註冊的命名空間。

+0

* next *的意思是*後面的*。可以在註冊後使用註冊的命名空間來調用'xpath()'方法。 – salathe 2012-03-22 18:50:29

+0

謝謝你花時間回覆,Jason。正如Salathe所說,問題在於CodeList在默認名稱空間而不是測試名稱空間中。 – fbc 2012-03-22 21:23:45

+0

夠公平的。有時候,當我不熟悉這些工具時,我只是拋出一些東西,看看有什麼棒。 – Jason 2012-03-22 23:30:44