【发布时间】:2013-03-16 19:41:09
【问题描述】:
如何只更改 DOM 节点的根标签名称?
在 DOM-Document 模型中,我们无法更改 DOMElement 对象的属性 documentElement,因此,我们需要“重建”节点......但是如何使用 childNodes 属性“重建”?
注意:我可以通过 converting to string with saveXML and cuting root by regular expressions 执行此操作...但这是一种解决方法,而不是 DOM 解决方案。
尝试过但不起作用,PHP 示例
PHP 示例(不起作用,但为什么?):
试一试
// 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");
}
appendChild($node) 导致错误:
Fatal error: Uncaught exception 'DOMException'
with message 'Wrong Document Error'
Try-2
来自@can 建议(仅指向链接)和我对可怜的dom-domdocument-renamenode manual 的解释。
function DomElement_renameRoot2($ele,$ROOTAG='newRoot') {
$ele->ownerDocument->renameNode($ele,null,"h1");
return $ele;
}
renameNode() 方法导致错误,
Warning: DOMDocument::renameNode(): Not yet implemented
Try-3
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'
【问题讨论】:
-
我添加了一个答案,该答案显示了如何执行此操作的函数,并且还轻轻指出了问题代码中的错误位置。一个更大的例子是我在其中链接的另一个答案:stackoverflow.com/a/16315039/367456
-
根标签通常被认为是文档元素或根节点。因此,您在问题中使用的措辞可能有点误导。您想重命名文档根元素的标记名还是只想重命名 domelements 标记名? (澄清问题)
标签: php xml domdocument appendchild removechild