我写了这个程序来从树中删除一个节点,但它仍然存在!
怎么会发生这种情况?打印节点内容后,它仍然显示与删除节点内容之前相同的内容,这意味着它仍然存在!
码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
节点从树中删除,但它确实作为节点存在,没有父节点.删除孩子后,再次执行此操作
d=document.getElementsByTagName("data1");
b=d.item(0);
System.out.println(b.getTextContent());
Run Code Online (Sandbox Code Playgroud)
您不会获得相同的文本内容(如果不同的data1标签具有不同的内容).