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

xiaoxiao2026-04-22  1

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(); } } 相关资源:Java 面经手册·小傅哥(公众号:bugstack虫洞栈).pdf
转载请注明原文地址: https://www.6miu.com/read-5047787.html

最新回复(0)