我的代码只是将新的Node和子Node添加到我的xml文件中,然后将其打印为输出。现在,如何在添加这些文件后再次保存xml文件
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse("src\\xpath\\Products.xml");
//make new node (product)
Element newproduct = document.createElement("product");
document.getDocumentElement().appendChild(newproduct);
//add attribute to the new product
newproduct.setAttribute("id", id);
//add name to the new product
Element newename = document.createElement("name");
newproduct.appendChild(newename);
newename.appendChild(document.createTextNode(name));
//add price to the new product
Element neweprice = document.createElement("price");
newproduct.appendChild(newename);
neweprice.appendChild(document.createTextNode(price));
// print XML
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
StreamResult console = new StreamResult(System.out);
transformer.transform(source, console);
System.out.println("\nNew Product added to product.xml.");
} catch (Exception e) {
System.err.println(e.getMessage());
}
代替打印到控制台
StreamResult console = new StreamResult(System.out);
保存到文件
StreamResult result = new StreamResult(new File("src\\xpath\\Products.xml"));
transformer.transform(source, result);