将所有子节点复制到另一个元素的本机方式

kro*_*oko 0 javascript xml dom clonenode clone

我必须更改XML的"未知"内容.结构和内容本身是有效的.原版的

<blabla foo="bar">
    <aa>asas</aa>
    <ff>
    <cc>
            <dd />
    </cc>
    </ff>
    <gg attr2="2">
    </gg>
    ...
    ...
</blabla>
Run Code Online (Sandbox Code Playgroud)

<blabla foo="bar">
    <magic>
        <aa>asas</aa>
        <ff>
        <cc>
            <dd />
        </cc>
        </ff>
        <gg attr2="2">
        </gg>
        ...
        ...
    </magic>
</blabla>
Run Code Online (Sandbox Code Playgroud)

因此,在文档根节点(document.documentElement)下直接添加子项并在其下"推送""原始"子项.这里必须用普通的javascript(ecmascript)来完成.

现在的想法是

// Get the root node
RootNode = mymagicdoc.documentElement;

// Create new magic element (that will contain contents of original root node)
var magicContainer = mymagicdoc.createElement("magic");

// Copy all root node children (and their sub tree - deep copy) to magic node
/* ????? here
    RootNodeClone = RootNode.cloneNode(true);
    RootNodeClone.childNodes......
*/

// Remove all children from root node
while(RootNode.hasChildNodes()) RootNode.removeChild(RootNode.firstChild);

// Now when root node is empty add the magicContainer
// node in it that contains all the children of original root node
RootNode.appendChild(magicContainer);
Run Code Online (Sandbox Code Playgroud)

怎么做/**/步?或者也许某人有更好的解决方案来实现理想的结果?
先感谢您!

答:通过maerics的解决方案完美无缺.

mae*_*ics 7

这样的东西应该适用于纯DOM和ECMAScript:

var blabla = mymagicdoc.documentElement
  , magic = mymagicdoc.createElement("magic");
while (blabla.hasChildNodes()) {
  magic.appendChild(blabla.removeChild(blabla.firstChild))
}
blabla.appendChild(magic);
Run Code Online (Sandbox Code Playgroud)