PHP - SimpleXML 故障排除中子节点的命名空间偏移

PHP - Namespace Shift in Child Node in SimpleXML Troubleshooting

我正在使用 SimpleXML 和 XPath 尝试获取子节点的 ('IndexEntry) 属性 ('indexKey') 的值。节点的命名空间,我在另一个节点上测试成功('Record')。 由于某种原因,此节点的属性 ('indexKey') 未返回。我已尝试使用子方法访问节点,同时指定其命名空间。

PHP代码

<?php
$url = "test_bb.xml";


$xml = simplexml_load_file($url);

$xml->registerXPathNamespace('a','http://www.digitalmeasures.com/schema/data');
$xml->registerXPathNamespace('dmd','http://www.digitalmeasures.com/schema/data-metadata');

$xml_report_abbrev_bb = $xml->xpath('//a:Record[@username="john-smith"]');

if($xml_report_abbrev_bb){
    echo '<br>CONTYPE is...'.$xml_report_abbrev_bb[0]->INTELLCONT->CONTYPE;
    echo '<br>termId is...'.$xml_report_abbrev_bb[0]['termId'].'<br>';
    echo '<br>surveyId is...'.$xml_report_abbrev_bb[0]->attributes('dmd',true)['surveyId'].'<br>';

//below - I've tried different methods of accessing the IndexEntry node...
    $dmd_fields = $xml_report_abbrev_bb[0]->children('dmd',true);
    echo '<br>dmd:IndexEntry is...'.$dmd_fields->IndexEntry['indexKey'].'<br>';

    echo '<br>dmd:IndexEntry is...'.$xml_report_abbrev_bb[0]->children('dmd',true)->IndexEntry['indexKey'].'<br>';

    //echo '<br>dmd:IndexEntry is...'.$xml_report_abbrev_bb[0]->IndexEntry('dmd',true)['indexKey'].'<br>';

    //echo '<br>dmd:IndexEntry is...'.$xml_report_abbrev_bb[0]->xpath('/dmd:indexEntry[@indexKey]')[0].'<br>';


} else {
    echo 'XPath query failed b';  
}

?>

XML ('test_bb.xml')

<?xml version="1.0" encoding="UTF-8"?>
<Data xmlns="http://www.digitalmeasures.com/schema/data" xmlns:dmd="http://www.digitalmeasures.com/schema/data-metadata" dmd:date="2012-01-03">
    <Record userId="148" username="john-smith" termId="4" dmd:surveyId="12">
        <dmd:IndexEntry indexKey="D" entryKey="Dylan" text="Dylan"/>
        <INTELLCONT id="14" dmd:originalSource="54TEX" dmd:lastModified="2017-04-18T10:54:29" dmd:startDate="2011-01-01" dmd:endDate="2011-12-31">
            <CONTYPE>Sales Tools</CONTYPE>
            <CONTYPEOTHER>Sales History</CONTYPEOTHER>
            </INTELLCONT>
    </Record>
</Data>

行中

$dmd_fields = $xml_report_abbrev_bb[0]->children('dmd', true);

这意味着 $dmd_fields 将是一个节点列表,即使列表中只有一个节点 - 因此使用 $dmd_fields[0] 来引用 <dmd:IndexEntry> 元素。因为这是 IndexEntry 元素,只需使用它和该元素的列表关闭属性,您就可以...

echo '<br>dmd:IndexEntry is...'.$dmd_fields[0]->attributes()['indexKey'].'<br>';

尽管 IndexEntry 元素位于 http://www.digitalmeasures.com/schema/data-metadata 命名空间中,由本地前缀 dmd: 表示,但其属性 没有前缀 :

<dmd:IndexEntry indexKey="D" entryKey="Dylan" text="Dylan"/>

本文档中未加前缀的 元素 位于 http://www.digitalmeasures.com/schema/data 命名空间中,如根节点上的 xmlns= 属性中所指定。

但是正如 discussed on this question,XML 命名空间规范指出属性永远不会在默认命名空间中。这使得它们特别地处于 根本没有命名空间 中,因此要使用 SimpleXML 访问它们,您必须 select URI 为空字符串的命名空间:

$dmd_fields->IndexEntry->attributes('')->indexKey;