简体   繁体   English

DOMXPath-获取节点

[英]DOMXPath - Get Node

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 : 我正在使用DOMXPath来检索以下XML文件的MsgId标记的值:

<?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: 以下是我用DOMXPath查询XML的PHP​​代码段:

$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? 有谁知道为什么xpath表达式在这种情况下不起作用? Am I missing some details here? 我在这里错过了一些细节吗?

$groupHeaderXPath is of type DOMXPath , which has a method registerNamespace . $groupHeaderXPath是类型的DOMXPath ,其具有方法registerNamespace

I think it would help to register the namespace and use the prefix 'urn' in your xpath expression. 我认为这将有助于注册名称空间并在xpath表达式中使用前缀“ urn”。

For example: 例如:

$rootNamespace = $document->lookupNamespaceUri($document->namespaceURI);
$groupHeaderXPath->registerNamespace("urn", $rootNamespace);
echo $groupHeaderXPath->query('//urn:GrpHdr/urn:MsgId')->length; // returns 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM