Java 怎么将XML文档(Document)保存到文件

2019年7月29日19:20:20Java 怎么将XML文档(Document)保存到文件已关闭评论 892 937字阅读3分7秒

1.简介

Java 怎么将XML文档(Document)保存到文件?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import org.w3c.dom.Document;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.*;

public class Main {

    public static void saveXML(File file, Document doc)
            throws TransformerException, IOException {
        DOMSource domSource = new DOMSource(doc);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        transformer = tf.newTransformer();
        
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(
                "{http:
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(domSource,
                new StreamResult(new OutputStreamWriter(
                        new FileOutputStream(file), "UTF-8")));
        
    }
}

 
继续阅读
编程十万个怎么办