3

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:

document.getXmlEncoding();

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

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

Thufir
  • 8,216
  • 28
  • 125
  • 273
  • Possible duplicate of [XML Document to String](https://stackoverflow.com/questions/5456680/xml-document-to-string) – fvu Jan 14 '19 at 18:28
  • I'm not saying it's not a duplicate, but the answer from ipsa is simpler than the linked answer. – Thufir Jan 14 '19 at 18:40
  • 1
    It's almost a complete copy except for some of the usual Java related IO nonsense but OK :) – fvu Jan 14 '19 at 19:00

1 Answers1

3

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!