2010-08-27 46 views
1

当我尝试在修改domdocument结构时尝试格式化xml输出时,我遇到了奇怪的行为。php domdocument奇怪的格式化

我已经创建了一个基于的DomDocument简单的项目类:

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文件,但是我注意到,在编辑文档之后,格式化会以某种方式丢失。它排序没有任何缩进等

<?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> 

我假设这是我在这里失踪的东西。也许这是我打开文档后将节点附加到根节点的方式,也许是一些魔术设置。

该代码完成这项工作,但我想知道这种奇怪行为的原因是什么。

回答

2

您可以“告诉”libxml前导/尾随空格不重要(因此在这种情况下,libxml可以将空格插入缩进元素),例如通过将preserveWhiteSpace属性设置为false。

$this->formatOutput = true; 
$this->preserveWhiteSpace = false; 
$this->root = $this->createElement("root"); 
+0

我知道这将是简单的事情:) 谢谢,它是有道理的,并按预期工作。 – Greg 2010-08-27 11:25:35