我在修改文档结构时尝试格式化xml输出时遇到了奇怪的行为。
我基于DomDocument创建了简单的Item类:
class Item extends DOMDocument {
private $root;
function __construct($version = null, $encoding = null) {
parent::__construct($version, $encoding);
$this->formatOutput = true;
$this->root = $this->createElement("root");
$this->root = $this->appendChild($this->root);
}
function build($name) {
$item = $this->createElement("item");
$name = $this->createTextNode($name);
$item->appendChild($name);
$this->getElementsByTagName("root")->item(0)->appendChild($item);
}
}
现在,我有一个小用例:
$it = new Item('1.0', 'iso-8859-1');
$it->build("first");
$it->build("seccond");
$xml = $it->saveXML();
echo $xml;
$it2 = new Item('1.0', 'iso-8859-1');
$it2->loadXML($xml);
$it2->build("third");
$it2->build("fourth");
$it2->build("fifth");
$it2->formatOutput = true;
$xml2 = $it2->saveXML();
echo $xml2;
<?xml version="1.0" encoding="iso-8859-1"?>
<root>
<item>first</item>
<item>seccond</item>
</root>
<?xml version="1.0" encoding="iso-8859-1"?>
<root>
<item>first</item>
<item>seccond</item>
<item>third</item><item>fourth</item><item>fifth</item></root>
我想这是我错过的东西。也许这是我在打开文档后将节点附加到根目录的方式,也许是一些神奇的设置。
代码起作用,但我想知道是什么原因导致这种奇怪的行为。