【问题标题】:How to declare an XML namespace prefix with DOM/PHP?如何使用 DOM/PHP 声明 XML 命名空间前缀?
【发布时间】:2010-08-27 13:51:05
【问题描述】:

我正在尝试通过 DOM/PHP5 生成以下 XML:

<?xml version="1.0"?>
<root xmlns:p="myNS">
  <p:x>test</p:x>
</root>

这就是我正在做的:

$xml = new DOMDocument('1.0');
$root = $xml->createElementNS('myNS', 'root');
$xml->appendChild($root);
$x = $xml->createElementNS('myNS', 'x', 'test');
$root->appendChild($x);
echo $xml->saveXML();

这就是我得到的:

<?xml version="1.0"?>
<root xmlns="myNS">
  <x>test</x>
</root>

我做错了什么?如何使这个前缀起作用?

【问题讨论】:

    标签: php xml dom xml-namespaces


    【解决方案1】:
    $root = $xml->createElementNS('myNS', 'root');
    

    root 不应在命名空间 myNS 中。在原始示例中,它不在命名空间中。

    $x = $xml->createElementNS('myNS', 'x', 'test');
    

    将qualifiedName 设置为p:x 而不仅仅是x,以向序列化算法建议您要使用p 作为此命名空间的前缀。但是请注意,对于具有命名空间的 XML 阅读器而言,无论是否使用 p:,在语义上都没有区别。

    这将导致xmlns:p 声明在&lt;p:x&gt; 元素(第一个需要它的元素)上输出。如果您希望声明位于根元素上(同样,与 XML-with-Namespaces 阅读器没有区别),您必须明确地 setAttributeNS 它。例如:

    $root = $xml->createElementNS(null, 'root');
    $xml->appendChild($root);
    $x = $xml->createElementNS('myNS', 'p:x', 'test');
    $root->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:p', 'myNS');
    $root->appendChild($x);
    

    【讨论】:

    • 哇,你解释得真好,这个答案真的帮助我理解了命名空间在 PHP DOM 中的真正工作原理!
    • @bobince 这是:stackoverflow.com/questions/61530580/… 与此问题相关吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 2017-04-09
    相关资源
    最近更新 更多