Search code examples
javaxmldomappendchild

How to save xml after I appendchild to it in java


my code just add new Node and child Nodes to my xml file , and then print it as output . Now How I can save the xml file again after these adds

 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());
    }

Solution

  • In place of printing to console

    StreamResult console = new StreamResult(System.out);
    

    save to file

    StreamResult result = new StreamResult(new File("src\\xpath\\Products.xml"));
    transformer.transform(source, result);