Reputation: 2552
I wrote this program to remove a node from tree, but it still exists!
How come this happenes? After printing the node content, it still shows the same content as before deleting it, which means it still exist!
Code:
public class JavaApplication38 {
public static void check(Node node){
if (node == null || node.getNodeName() == null)
return;
check(node.getFirstChild());
System.out.println(node.getNodeValue() != null && node.getNodeValue().trim().length() == 0 ? "" : node);
if ( "abcd".equals(node.getTextContent()))
node.getParentNode().removeChild(node);
check(node.getNextSibling());
}
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
File file = new File("d:\\a.xml");
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
document.getDocumentElement().normalize();
Node b=document.getFirstChild();
check(b);
check(b);
}
}
Upvotes: 2
Views: 321
Reputation: 8245
No, the node is removed.
Removing the node from the tree does automatically delete it.
To see if the node is properly removed, you could write some code for printing the tree.
EDIT:
I'm not sure if your check
method visits every node in the tree.
And I would suggest separating the code that prints the tree from the code that modifies it; then call
printTree(d);
modifyTree(d);
printTree(d);
You seem to know and understand recursion, so you should be able to write a method that prints the tree.
Upvotes: 2
Reputation: 6052
The node is deleted from the Tree, but it does exist as a node, with no parent. after removing child, do this again
d=document.getElementsByTagName("data1");
b=d.item(0);
System.out.println(b.getTextContent());
You wont get the same text content (if different data1
tags have different contents).
Upvotes: 5