如何将 DOM 文档写入文件?

How do I write a DOM Document to File?

如何将此 document 写入本地文件系统?

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

我需要迭代 document,或者可能有 "to xml/html/string" 方法?我在看:

document.getXmlEncoding();

不是 quite 我所追求的——而是类似的东西。寻找 String 表示,然后将其写入文件,如:

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

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

我会使用转换器 class 将 DOM 内容转换为 xml 文件,如下所示:

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

我希望这对你有用!