【问题标题】:Get Namespace Name in Root Element via PHP SimpleXMLElement通过 PHP SimpleXMLElement 获取根元素中的命名空间名称
【发布时间】:2015-11-30 01:53:35
【问题描述】:

假设我有以下 XML(这是 ATOM 的标准)

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

    <title>Example Feed</title>
    <subtitle>A subtitle.</subtitle>
    <link href="http://example.org/feed/" rel="self" />
    <link href="http://example.org/" />
    <id>urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6</id>
    <updated>2003-12-13T18:30:02Z</updated>


    <entry>
        <title>Atom-Powered Robots Run Amok</title>
        <link href="http://example.org/2003/12/13/atom03" />
        <link rel="alternate" type="text/html" href="http://example.org/2003/12/13/atom03.html"/>
        <link rel="edit" href="http://example.org/2003/12/13/atom03/edit"/>
        <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
        <updated>2003-12-13T18:30:02Z</updated>
        <summary>Some text.</summary>
        <content type="xhtml">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <p>This is the entry content.</p>
            </div>
        </content>
        <author>
            <name>John Doe</name>
            <email>johndoe@example.com</email>
        </author>
    </entry>

</feed>

另外,假设上面的XML在一个地址为http://www.example.com/atom.xml的网页中

我知道您可以通过以下代码获取根元素名称:

// Using curl to access the page
$ch = curl_init('http://www.example.com/atom.xml');
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);

$xml = new SimpleXmlElement($result);
$root = $xml->getName();
echo ($root)  // This prints "feed", which is the root element

另外,我知道下面的调用会获取所有的根命名空间。

$xml->getNamespaces(true)

在我们的例子中,返回值为:

Array
(
    [] => http://www.w3.org/2005/Atom
)

但是,我真的很想知道命名空间的名称。换句话说,我不知道调用哪个函数会返回 xmlns。我如何知道命名空间的名称?我需要它在处理之前进行一些验证。

请帮忙,谢谢。

【问题讨论】:

  • 你错了,用于命名空间的别名/前缀不相关。如果你验证它,验证就会被破坏。命名空间是http://www.w3.org/2005/Atomcontent 中的div 节点是http://www.w3.org/1999/xhtml

标签: php xml namespaces simplexml xml-namespaces


【解决方案1】:

“但是,我真的很想知道命名空间的名称。换句话说,我不知道调用哪个函数会返回 xmlns。 p>

xmlns 是命名空间声明的默认属性名称的 XML 语法。目前尚不清楚您要验证什么,但我认为可以安全地假设,如果 getNamespaces() 返回前缀为空的命名空间,则源 XML 具有有效的默认命名空间(换句话说,源 XML 具有xmlns)。

引用 W3C "Namespaces in XML" 以方便参考:

  1. 如果属性名称与DefaultAttName 匹配,则属性值中的名称空间名称是附加声明的元素范围内的默认名称空间名称。在这样的默认声明中,属性值可能为空。 “5. 将命名空间应用于元素和属性”中讨论了默认命名空间和声明的覆盖。 [Default Namespace]

  2. [3] DefaultAttName ::= 'xmlns' 。 [Default Attribute Name]

【讨论】:

  • 我对 xmlns 有误解,您的回答很有帮助。谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多