gpt4 book ai didi

java - 在java中追加子项后如何保存xml

转载 作者:行者123 更新时间:2023-12-01 16:19:03 24 4
gpt4 key购买 nike

我的代码只是将新节点和子节点添加到我的 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);

关于java - 在java中追加子项后如何保存xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62318313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com