Java 怎么将DOM文档写入XML文件

2019年7月29日19:38:17Java 怎么将DOM文档写入XML文件已关闭评论 640 1753字阅读5分50秒

1.简介

Java 怎么将DOM文档写入XML文件?——请看下文。

2.示例代码

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

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
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 org.w3c.dom.Document;

public class Main{
    private static Logger logger = Logger
            .getLogger(XMLUtil.class.getName());
    
    public static void writeDocumentToXml(Document doc, String fileName)
            throws TransformerException, IOException {
        File file = new File(fileName);
        if (!file.exists())
            file.createNewFile();
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(fileName);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");

        
        if (logger.isLoggable(Level.FINE))
            logger.fine(result.toString());

        transformer.transform(source, result);
    }
    
    public static void writeDocumentToXml(Document doc, File file)
            throws TransformerException, IOException {
        if (!file.exists())
            file.createNewFile();
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(file.toURI().getPath());
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
        transformer.setOutputProperty(
                "{http:

        
        if (logger.isLoggable(Level.FINE))
            logger.fine(result.toString());

        transformer.transform(source, result);
    }
}

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