简体   繁体   中英

How to save a new created DOM document file as .xml in java?

I create a new DOM document file using following lines of code:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    File file = iniFilePath.toFile();
    if (file.exists()) {
        doc = builder.parse(file);

    } else {
        doc = builder.newDocument();
        doc.appendChild(doc.createElement("windows"));
        //I want to save .xml here
    }

Now, I want to save the new created DOM document to an .xml file. How can I achieve this?

You could use transformers :

Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult( new File("path_to_xml.xml") );
Source input = new DOMSource( doc );
transformer.transform( input, output );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM