从 DOM 中删除节点
我编写了这个程序来从树中删除一个节点,但它仍然存在!
怎么会出现这样的情况呢?打印节点内容后,仍然显示与删除之前相同的内容,这意味着它仍然存在!
代码:
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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该节点已从树中删除,但它确实作为节点存在,没有父节点。删除子项后,再次执行此操作
您将不会获得相同的文本内容(如果不同的
data1
标签具有不同的内容)。The node is deleted from the Tree, but it does exist as a node, with no parent. after removing child, do this again
You wont get the same text content (if different
data1
tags have different contents).否,节点已被删除。
从树中删除节点会自动删除它。
要查看节点是否已正确删除,您可以编写一些代码来打印树。
编辑:
我不确定您的
check
方法是否访问树中的每个节点。我建议将打印树的代码与修改树的代码分开;然后调用
你似乎知道并理解递归,所以你应该能够编写一个打印树的方法。
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
You seem to know and understand recursion, so you should be able to write a method that prints the tree.