我正在尝试清除包含字符串“ s”的xml行。我已经实现了此方法,但它只删除了一半的行。
public void clearResults(String s) {
try {
File inputFile = new File("src/resources/config.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
for(int i=0; i<doc.getElementsByTagName(s).getLength(); i++) {
Element element = (Element) doc.getElementsByTagName(s).item(i);
element.getParentNode().removeChild(element);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new FileOutputStream(inputFile));
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
}
} catch (Exception e) {
e.printStackTrace();
}
}