Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a DOM Document to File?

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

like image 368
Thufir Avatar asked Mar 13 '26 23:03

Thufir


1 Answers

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!

like image 200
ipsa scientia potestas Avatar answered Mar 15 '26 12:03

ipsa scientia potestas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!