How do I write a DOM Document to File?

Thufir :

How do I write this document to the local filesystem?

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

I need to iterate the document, or might there be a "to xml/html/string" method? I was looking at:


Not quite what I'm after -- but something like that. Looking for the String representation and then to write that to file like:

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

ipsa scientia potestas :

I would use a transformer class to convert the DOM content to an xml file, something like below:

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 ends up working for you!

Guess you like