如何更改DOM中元素的名称? [英] How can I change the name of an element in DOM?
问题描述
在有PHP的PHP中,我有一个DomElement对象,表示一个< identity />元素。我有一种情况需要改变它,元素名称为< person />,但保持相同的子元素和属性。
最简单的方法是更改DomElement的元素名称并保留其孩子和属性?
编辑:我刚刚发现了一个非常相似的问题(虽然它没有很好的答案)。
可以使用 importNode()
复制< identity>
元素到新创建的< person>
元素
function changeName($ node,$ name){
$ newnode = $ node-> ownerDocument-> createElement($ name);
foreach($ node-> childNodes as $ child){
$ child = $ node-> ownerDocument-> importNode($ child,true);
$ newnode-> appendChild($ child,true);
}
foreach($ node->属性为$ attrName => $ attrNode){
$ newnode-> setAttribute($ attrName,$ attrNode);
}
$ newnode-> ownerDocument-> replaceChild($ newnode,$ node);
return $ newnode;
}
$ domElement = changeName($ domElement,'person');
也许这样的东西可以工作,或者你可以尝试使用 cloneChild()
。
编辑:其实,我只是意识到原来的功能会丢失节点的位置。根据thomasrutter链接的问题,应该使用 replaceChild()
。
In PHP with DOM, I have a DomElement object which represents an <identity/> element.
I have one case where I need to change this so its element name is <person/>, but keep the same child elements and attributes.
What would be the simplest way of changing an element name of a DomElement and keeping its children and attributes?
Edit: I have just found a very similar question (though it doesn't have very good answers).
Could you use importNode()
to copy the childNodes of your <identity>
element to a newly created <person>
element?
function changeName($node, $name) {
$newnode = $node->ownerDocument->createElement($name);
foreach ($node->childNodes as $child){
$child = $node->ownerDocument->importNode($child, true);
$newnode->appendChild($child, true);
}
foreach ($node->attributes as $attrName => $attrNode) {
$newnode->setAttribute($attrName, $attrNode);
}
$newnode->ownerDocument->replaceChild($newnode, $node);
return $newnode;
}
$domElement = changeName($domElement, 'person');
Perhaps something like that would work, or you could try using cloneChild()
.
Edit: Actually, I just realized that the original function would lose the placement of the node. As per the question thomasrutter linked to, replaceChild()
should be used.
这篇关于如何更改DOM中元素的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!