如何使用指定自身命名空间的节点生成xml?

时间:2012-10-13 02:41:32

标签: php xml dom domdocument

这是我想要的结果:

<?xml version="1.0" encoding="utf-8"?>
<types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"/>
</types>

但使用直截了当的解决方案:

$document = new DOMDocument('1.0', 'utf-8');

$schema = $document->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:schema');

$types = $document->createElement('types');
$types->appendChild($schema);

$document->appendChild($types);

echo $document->saveXML();

我只能得到这个:

<?xml version="1.0" encoding="utf-8"?>
<types xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"/>
</types>

我错过了什么?

1 个答案:

答案 0 :(得分:4)

问题在于追加孩子。试试这个:

$document = new DOMDocument('1.0', 'utf-8');

$types = $document->createElement('types');
$schema = $document->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:schema');

$document->appendChild($types);
$types->appendChild($schema);

echo $document->saveXML();