从XML中读取属性值,其中包含元素名称和属性名称中带冒号的前缀

时间:2017-09-04 13:32:44

标签: php xml xpath

我在XML中有元素,如下所示

<user:name test:one = "firstUser" />

我使用 PHP DOM Xpath 来读取XML

$ doc = new DOMDocument();

$xpath = new DOMXPath($doc);
$xml = simplexml_load_file(file path here);
echo '<pre>'; print_r($xml);

,输出为空白

SimpleXMLElement Object
(
)

如果我尝试删除和前缀如下

<name one = "firstUser" /> 

然后它读取元素。输出

SimpleXMLElement Object
(
    [name] => SimpleXMLElement Object
    (
        [@attributes] => Array
        (
            [one] => firstUser
        )
    )
)

如何使用前缀和冒号(:)

读取元素值

更新:示例XML文件

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:test="http://www.w3.org/2001/XMLSchema"  xmlns:user="http://www.w3.org/2001/XMLSchema">
    <user:name test:one = "firstUser" />
    <name second = "secondUser" />
</root>

1 个答案:

答案 0 :(得分:2)

使用DOMDocument浏览文档:

<?php
$doc = new DOMDocument();
$doc->load("file.xml");
$root = $doc->getElementsByTagName("root");
echo "<pre>";
foreach ($doc->getElementsByTagName("name") as $users) {
    echo $users->nodeName.":";
    foreach ($users->attributes as $attr) {
        echo $attr->name." ".$attr->value."<br>";
    }
    echo "<br>";
}

Demo (XML loaded from string)

相关问题