欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

删除根节点下的所有子节点

程序员文章站 2022-06-08 09:07:41
...
public static void toDelete(){

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

try{

DocumentBuilder db = factory.newDocumentBuilder();

File file = new File(path);

Document doc = db.parse(file);

NodeList le = doc.getChildNodes();

for (int i = 0; i < le.getLength(); i++) {
Element e = (Element) le.item(i);

NodeList childList = e.getChildNodes();
int n = childList.getLength();
for (int j = 0; j < n; j++) {
Node node = childList.item(j);
if (node != null) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(node.getNodeName());
Node parentNode = node.getParentNode();
parentNode.removeChild(node);
}
}
}
}
HandleXML.saveXml(path, doc);

}catch(Exception e){

e.printStackTrace();

}

}
相关标签: J#