【发布时间】:2019-03-25 01:33:48
【问题描述】:
我使用 PHP DOMDocument 来生成 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> 中?以及如何防止重复?
【问题讨论】:
标签: php xml domdocument