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

How to save xml after I appendchild to it in java

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