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");
}
The replaceChild() method is used to replace a node.
JAVA provides excellent support and a rich set of libraries to parse, modify or inquire XML documents.
Remove a Text Node Set the variable x to be the first title element node. Set the variable y to be the text node to remove. Remove the element node by using the removeChild() method from the parent node.
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);
}
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