Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite root element

Tags:

java

dom

xml

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.

like image 687
travega Avatar asked Mar 15 '26 11:03

travega


1 Answers

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);
like image 148
Marvin Pinto Avatar answered Mar 17 '26 23:03

Marvin Pinto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!