如何覆盖根元素

3

我遇到了这样的情况,需要在w3c dom中创建一个新元素,并将其覆盖掉根(Document)元素。到目前为止,我已经尝试了两种不同的方法来实现这个目标:

document.removeChild(document.getDocumentElement());

随后出现了这样的情况:
newElement = document.getDocumentElement();
newElement = document.createElement("newRootElementName");
document.appendChild(newElement);

似乎两者都没有覆盖根元素,并且在保存后,文档似乎只包含空的根元素。


3
我对JavaScript解决方案不感兴趣。我对Java的解决方案感兴趣,并且已经使用了相关的标签。 - travega
1个回答

6
根据我在这里找到的示例,以下是如何操作的。由于似乎没有更改元素名称的方法,因此您需要执行以下操作:
  1. 创建另一个具有新名称的元素
  2. 复制旧元素的属性
  3. 复制旧元素的子元素
  4. 最后替换节点。
例如:
// Obtain the root element
Element element = document.getDocumentElement();

// Create an element with the new name
Element element2 = document.createElement("newRootElementName");

// Copy the attributes to the new element
NamedNodeMap attrs = element.getAttributes();
for (int i=0; i<attrs.getLength(); i++) {
  Attr attr2 = (Attr)document.importNode(attrs.item(i), true);
  element2.getAttributes().setNamedItem(attr2);
 }

// Move all the children
while (element.hasChildNodes()) {
  element2.appendChild(element.getFirstChild());
 }

// Replace the old node with the new node
element.getParentNode().replaceChild(element2, element);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接