如何只更改 DOM 节点的根标签名称?
在 DOM-Document 模型中我们无法更改属性documentElement
of a DOMElement
对象,所以,我们需要“重建”节点......但是如何“重建”childNodes
财产?
注意:我可以通过以下方式做到这一点使用saveXML转换为字符串并通过正则表达式切割根...但它是一种解决方法,而不是 DOM 解决方案。
尝试过但不起作用,PHP 示例
PHP 示例(不起作用,但为什么?):
Try-1
// DOMElement::documentElement can not be changed, so...
function DomElement_renameRoot1($ele,$ROOTAG='newRoot') {
if (gettype($ele)=='object' && $ele->nodeType==XML_ELEMENT_NODE) {
$doc = new DOMDocument();
$eaux = $doc->createElement($ROOTAG); // DOMElement
foreach ($ele->childNodes as $node)
if ($node->nodeType == 1) // DOMElement
$eaux->appendChild($node); // error!
elseif ($node->nodeType == 3) // DOMText
$eaux->appendChild($node); // error!
return $eaux;
} else
die("ERROR: invalid DOM object as input");
}
The appendChild($node)
导致错误:
Fatal error: Uncaught exception 'DOMException'
with message 'Wrong Document Error'
Try-2
来自@can的建议(仅指向链接)和我对穷人的解释dom-domdocument-renamenode 手册.
function DomElement_renameRoot2($ele,$ROOTAG='newRoot') {
$ele->ownerDocument->renameNode($ele,null,"h1");
return $ele;
}
renameNode() 方法导致错误,
Warning: DOMDocument::renameNode(): Not yet implemented
Try-3
From PHP手册,注释1.
function renameNode(DOMElement $node, $newName)
{
$newNode = $node->ownerDocument->createElement($newName);
foreach ($node->attributes as $attribute)
$newNode->setAttribute($attribute->nodeName, $attribute->nodeValue);
while ($node->firstChild)
$newNode->appendChild($node->firstChild); // changes firstChild to next!?
$node->ownerDocument->replaceChild($newNode, $node); // changes $node?
// not need return $newNode;
}
ReplaceChild() 方法导致错误,
Fatal error: Uncaught exception 'DOMException' with message 'Not Found Error'