重复 xml 个命名空间声明 php DOMDocument

Duplicate xml namespace declarations php DOMDocument

我用PHPDOMDocument生成xml。有时命名空间仅在根元素上声明,这是预期的行为,但有时不是。 例如:

$xml = new DOMDocument('1.0', 'utf-8');
$ns = "http://ns.com";
$otherNs = "http://otherns.com";
$docs = $xml->createElementNS($ns, "ns:Documents");
$doc = $xml->createElementNS($otherNs, "ons:Document");
$innerElement = $xml->createElementNS($otherNs, "ons:innerElement", "someValue");
$doc->appendChild($innerElement);
$docs->appendChild($doc);
$xml->appendChild($docs);
$xml->formatOutput = true;
$xml->save("dom");

我预计:

<?xml version="1.0" encoding="UTF-8"?>
<ns:Documents xmlns:ns="http://ns.com" xmlns:ons="http://otherns.com">
  <ons:Document>
    <ons:innerElement>someValue</ons:innerElement>
  </ons:Document>
</ns:Documents>

但是得到了:

<?xml version="1.0" encoding="UTF-8"?>
<ns:Documents xmlns:ns="http://ns.com" xmlns:ons="http://otherns.com">
  <ons:Document xmlns:ons="http://otherns.com">
    <ons:innerElement>someValue</ons:innerElement>
  </ons:Document>
</ns:Documents>

为什么 xmlns:ons="http://otherns.com" 的声明出现在 Document 元素上,而不是 <innerElement> 中?以及如何防止重复?

这很容易。只需将您的节点添加到文档树中。 此外,您可以在根节点中显式创建 xmlns:XXX 属性。 参见示例:

namespace test;

use DOMDocument;

$xml = new DOMDocument("1.0", "UTF-8");

$ns = "http://ns.com";
$otherNs = "http://otherns.com";

$docs = $xml->createElementNS($ns, "ns:Documents");
$xml->appendChild($docs);

$docs->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ons', $otherNs);

$doc = $xml->createElement("ons:Document");
$docs->appendChild($doc);

$innerElement = $xml->createElement("ons:innerElement", "someValue");
$doc->appendChild($innerElement);


$xml->formatOutput = true;

echo $xml->saveXML();

结果:

<?xml version="1.0" encoding="UTF-8"?>
<ns:Documents xmlns:ns="http://ns.com" xmlns:ons="http://otherns.com">
  <ons:Document>
    <ons:innerElement>someValue</ons:innerElement>
  </ons:Document>
</ns:Documents>