我编写了这个程序来从树中删除一个节点,但它仍然存在!
怎么会发生这种情况?打印节点内容后,它仍然显示与删除节点内容之前相同的内容,这意味着它仍然存在!
代码:
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);
}
}
答案 0 :(得分:5)
节点从树中删除,但它确实作为节点存在,没有父节点。删除孩子后,再次执行此操作
d=document.getElementsByTagName("data1");
b=d.item(0);
System.out.println(b.getTextContent());
您不会获得相同的文本内容(如果不同的data1
标签具有不同的内容)。
答案 1 :(得分:2)
不,删除节点 从树中删除节点会自动删除它。
要查看节点是否已正确删除,您可以编写一些代码来打印树。
编辑:
我不确定您的check
方法是否访问了树中的每个节点
我建议将打印树的代码与修改它的代码分开;然后打电话
printTree(d);
modifyTree(d);
printTree(d);
你似乎知道并理解递归,所以你应该能够编写一个打印树的方法。