Java 如何将DOM文档写入文件?

Java 如何将DOM文档写入文件?,java,file,dom,file-io,domdocument,Java,File,Dom,File Io,Domdocument,如何将此文档写入本地文件系统 public void docToFile(org.w3c.dom.Document document, URI path) throws Exception { File file = new File(path); } 我需要迭代文档,或者可能有一个“to-xml/html/string”方法?我在看: document.getXmlEncoding(); 不是我想要的,而是类似的东西。查找字符串表示,然后将其写入文件,如: Path file =

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

public void docToFile(org.w3c.dom.Document document, URI path) throws Exception {
    File file = new File(path);
}
我需要迭代
文档
,或者可能有一个“to-xml/html/string”方法?我在看:

document.getXmlEncoding();

不是我想要的,而是类似的东西。查找
字符串
表示,然后将其写入文件,如:

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

我将使用transformer类将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);


我希望这最终对你有用

可能的重复我不是说它不是重复的,但是ipsa的答案比链接的答案更简单。它几乎是一个完整的副本,除了一些常见的Java相关IO废话,但OK:)