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!!!
The renameNode() method renames an existing element or attribute node. When possible, this changes the name of the given node, otherwise this creates a new node with the specified name and replaces the existing node with the new node.
Get the Document Element using getDocumentElement() API method of Document. Create a new Element, using createElement(String tagName ) API method of Document. Append the new node at the end of list of children of the Document Element, with appendChild(Node newChild) API method of Node.
Indicates the name of the XML element or attribute representing the ProDataSet, the temp-table, the temp-table buffer, or the temp-table buffer-field object name in an XML document. This attribute's purpose overlaps with the SERIALIZE-NAME attribute.
Using Document.renameNode:
NodeList nodes = document.getElementsByTagName("tag1");
for (Node eachNode: nodes) {
document.renameNode(eachNode, null, "reallyCoolTag");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With