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

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#)