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");
}