travega
travega

Reputation: 8415

How to overwrite root element

I have a come to a scenario whereby I need to overwrite the root (w3c dom) Document element with a new element after it has been created elsewhere. So far I have tried two different ways of achieving this:

document.removeChild(document.getDocumentElement());

AND subsequently this:

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

Neither seem to overwrite the root element, and, after saving, the document seems only to contain the root element that is empty.

Upvotes: 3

Views: 4593

Answers (1)

Marvin Pinto
Marvin Pinto

Reputation: 30990

Going with the example I found here, here's how you could do it. Since there's apparently no method to change the name of an element, you would have to do the following:

  1. Create another element with the new name
  2. Copy the old element's attributes
  3. Copy the old element's children
  4. And finally replace the node.

For example:

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

Upvotes: 6

Related Questions