Replacing XML node through Java

I want to replace the node in the XML document with another and, as a result, replace all its children with other content. The following code should work, but for some unknown reason it is not.

File xmlFile = new File("c:\\file.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("NodeToReplace"); for (int i = 0; i < nodes.getLength(); i++) { NodeList children = nodes.item(i).getChildNodes(); for (int j = 0; j < children.getLength(); j++) { nodes.item(i).removeChild(children.item(j)); } doc.renameNode(nodes.item(i), null, "MyCustomTag"); } 

EDIT -

After some debugging, I tricked him. The problem was moving the index of children's ranks. Here is the code:

 NodeList nodes = doc.getElementsByTagName("NodeToReplace"); for (int i = 0; i < nodes.getLength(); i++) { NodeList children = nodes.item(i).getChildNodes(); int len = children.getLength(); for (int j = len-1; j >= 0; j--) { nodes.item(i).removeChild((Node) children.item(j)); } doc.renameNode(nodes.item(i), null, "MyCustomTag"); } 
+4
source share
1 answer

Try using replaceChild to run the entire hierarchy at once:

 NodeList nodes = doc.getElementsByTagName("NodeToReplace"); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); Node newNode = // Create your new node here. node.getParentNode().replaceChild(newNode, node); } 
+8
source

All Articles