有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何覆盖根元素

我遇到了一个场景,在其他地方创建根(W3CDOM)文档元素后,我需要用新元素覆盖它。到目前为止,我已经尝试了两种不同的方法来实现这一点:

document.removeChild(document.getDocumentElement());

随后:

newElement = document.getDocumentElement();
newElement = document.createElement("newRootElementName");
document.appendChild(newElement);

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


共 (1) 个答案

  1. # 1 楼答案

    按照我找到的here的例子,下面是如何做到这一点的。由于显然没有更改元素名称的方法,因此必须执行以下操作:

    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);