Changing node name of xml-node with Java

doro picture doro · Aug 19, 2009 · Viewed 28.1k times · Source

I have following scenario: I have a XML-Document, e.g. like this

<someRootElement>
<tag1>
    <tag2 
        someKey=someValue
        someKey2=someValue2
    />
    <tag3/>
    <tag4
        newKey=newValue
        newKey2=newValue2
    />
</tag1>
</someRootElement>

Now I want the parent tag1 to be called reallyCoolTag without losing the childnodes. I tried the following, but it unfortunately doesn't work as I wish it would (but I do know why, b/c it is missing something, I guess):

// the new element:
Element neu = doc.createElement( newValue );
// append it to the root:
root.appendChild( neu );
// get all the child nodes:
NamedNodeMap nnm = nodes.item(i).getAttributes();
for( int dg = 0; dg < nnm.getLength(); dg++ ){
    neu.setAttribute(  nnm.item( dg ).getNodeName(),
    nnm.item( dg ).getNodeValue() );
}
//---------------------------------------------------------
// HERE I GUESS I AM MISSING THE PART WHERE THE CHILD NODES
// ARE BEING APPENDED TO THE NEW NODE?????
//---------------------------------------------------------
// nodes.item(i) := the old value (nodes := is a NodeList
root.replaceChild( neu, nodes.item(i));
TransformerFactory tFactory     = TransformerFactory.newInstance();
Transformer transformer         = tFactory.newTransformer();
DOMSource source                = new DOMSource( doc );
StreamResult result         = new StreamResult( xml );
transformer.transform( source, result );
nodes.item( i ).getParentNode().removeChild( nodes.item(i) );

Now this does work to a certain extend, as I mentioned, I guess I am missing the part where the child nodes are being appened, but what I actually wanted to know is, whether there is a really short way to rename the parent node without having to copy everything and replace the whole thing?

Thnx in advance!!!

Answer

McDowell picture McDowell · Aug 22, 2009

Using Document.renameNode:

NodeList nodes = document.getElementsByTagName("tag1");
for (Node eachNode: nodes) {
  document.renameNode(eachNode, null, "reallyCoolTag");
}