Java – How do I write a DOM document to a file?

How do I write a DOM document to a file?… here is a solution to the problem.

How do I write a DOM document to a file?

How do I write this document to my local file system?

public void docToFile(org.w3c.dom.Document document, URI path) throws Exception {
    File file = new File(path);
}

Do I need to iterate over the document, or maybe there is a “to xml/html/string” method? I’m watching:

document.getXmlEncoding();

Not quite what I’m after—but something like that. Look for the String representation and write it to a file, such as :

Path file = ...;
byte[] buf = ...;
Files.write(file, buf);

https://docs.oracle.com/javase/tutorial/essential/io/file.html

Solution

I’ll use the converter class to convert the DOM content to an xml file like this:

Document doc =...

 write the content into xml file

DOMSource source = new DOMSource(doc);
    FileWriter writer = new FileWriter(new File("/tmp/output.xml"));
    StreamResult result = new StreamResult(writer);

TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(source, result);

I hope this works for you in the end!

Related Problems and Solutions