我写了这个程序从树中删除了一个节点,但它仍然存在!从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);
}
}
等等,Java也有这个愚蠢的'node.parentNode.removeChild(node)'模式? –
@Šime:如果您使用DOM API的Java实现,您当然必须忍受DOM API中的所有缺陷。但是对于XML处理通常有更好的选择。 – jarnbjo