如何将DOM文档写入文件?

时间:2019-01-14 18:20:48

标签: java file dom file-io domdocument

如何将此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

1 个答案:

答案 0 :(得分:1)

我将使用转换器类将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);

希望这对您有用!