【问题标题】:Read attribute value from XML which contains prefix with colon in element name and attribute name从 XML 中读取属性值,其中元素名称和属性名称中包含带有冒号的前缀
【发布时间】:2017-09-04 13:32:44
【问题描述】:

我在 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>

【问题讨论】:

标签: php xml xpath


【解决方案1】:

使用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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 2019-07-09
    • 2012-06-09
    • 1970-01-01
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多