我在Java中附加子级后如何保存xml

问题描述 投票:0回答:1

我的代码只是将新的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());
    }
java xml dom appendchild
1个回答
0
投票

代替打印到控制台

StreamResult console = new StreamResult(System.out);

保存到文件

StreamResult result = new StreamResult(new File("src\\xpath\\Products.xml"));
transformer.transform(source, result);
© www.soinside.com 2019 - 2024. All rights reserved.