Xpath with namespace

I am trying to use xpath in php SimpleXML with an xml file, of which the following is the corresponding fragment: -

<?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. 

In my php code, I have the following which registers the namespace and then uses xpath to get the CodeLists: $ Xml-> registerXPathNamespace ('test', 'HTTP://www.SDMX.org/resources/SDMXML/schemas/ v2_0 / message ');

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

I would like to be able to use xpath to go one level lower in the tree, i.e. in CodeList, and thought the following would work: -

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

But it just creates an empty array. I cannot find access to anything else in the document using xpath. I spent several hours trying to solve this problem, so any help would be greatly appreciated.

+2
source share
2 answers

CodeList elements belong to the default namespace inherited from the <message:Structure> element - a namespace whose URI is http://www.SDMX.org/resources/SDMXML/schemas/v2_0/structure .

You also need to register this with registerXPathNamespace() .

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

It seems that registerXPathNamespace only works for the next xpath request (as per the documentation ) ... so if you run $xml->xpath('test:CodeLists') already try registering the namespace again before running $xml->xpath('test:CodeLists/CodeList') .

0
source

Source: https://habr.com/ru/post/951353/


All Articles