I'm facing an issue that I cannot resolve. I'm using DOMXPath to retrieve the value of MsgId
tag of the following XML file :
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CstmrCdtTrfInitn>
<GrpHdr>
<MsgId>Test/20171013/CCT100621</MsgId>
<CreDtTm>2017-10-13T10:06:21</CreDtTm>
<NbOfTxs>62</NbOfTxs>
</GrpHdr>
</CstmrCdtTrfInitn>
</Document>
The following is my PHP code snippet to query the XML with DOMXPath:
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CstmrCdtTrfInitn>
<GrpHdr>
<MsgId>Test/20171013/CCT100621</MsgId>
<CreDtTm>2017-10-13T10:06:21</CreDtTm>
<NbOfTxs>62</NbOfTxs>
</GrpHdr>
</CstmrCdtTrfInitn>
</Document>
XML;
$document = new DOMDocument;
$document->loadXML($xml);
$groupHeaderXPath = new DOMXPath($document);
echo $groupHeaderXPath->query('//GrpHdr/MsgId')->length; // returns 0
I'm testing the query with this tool and it seems that it is correct.
Has anybody an idea, why the xpath expression does not work in this context? Am I missing some details here?
$groupHeaderXPath
is of type DOMXPath , which has a method registerNamespace .
I think it would help to register the namespace and use the prefix 'urn' in your xpath expression.
For example:
$rootNamespace = $document->lookupNamespaceUri($document->namespaceURI);
$groupHeaderXPath->registerNamespace("urn", $rootNamespace);
echo $groupHeaderXPath->query('//urn:GrpHdr/urn:MsgId')->length; // returns 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.