开发者

How to clone a node and use it as documentElement for a new DOMDocument?

In PHP5, I have a DOMDocument ($xmlDoc1). Let's say its do开发者_如何学PythoncumentElement is: <root id="1" type=""/>. I create a new DOMDocument $xmlDoc2.

What I need to do is clone $xmlDoc1's documentElement (with its attributes but not its children), and use it as the documentElement for $xmlDoc2.

In ASP, you could write :

XMLDoc2.DocumentElement = XMLDoc1.DocumentElement.CloneNode(False)

PHP DOM has a cloneNode() method, but doesn't allow to append the cloned node to another document.

How could I do it?


Have a look at:

http://php.net/manual/en/domdocument.importnode.php

Example:

<?php
$dom = new DomDocument();
$dom->loadXml('<root attr1="a" attr2="b"><foo></foo></root>');

$dom2 = new DomDocument();
$dom2->appendChild(
    $dom2->importNode($dom->documentElement->cloneNode(false), true) 
);

header('Content-Type: text/xml; charset="UTF-8"');
echo $dom2->saveXml();

Executed:

http://codepad.org/yCFegZbp

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜