Replacing XML node via Java
19,414
Try using replaceChild to do the whole 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);
}
Author by
Ondrej Sotolar
I'm a computer science student; often battling with Java, C#, Haskell, algorithms, and others. I currently work as a C# developer.
Updated on July 11, 2022Comments
-
Ondrej Sotolar almost 2 years
I wan to replace a node in XML document with another and as a consequence replace all it's children with other content. Following code should work, but for an unknown reason it doesn't.
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 debugging it for a while, I sovled it. The problem was in moving index of the children array elmts. Here's 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"); }