Java 怎么将DOM保存到文件

2019年7月29日19:35:26Java 怎么将DOM保存到文件已关闭评论 954 1598字阅读5分19秒

1.简介

Java 怎么将DOM保存到文件?——请看下文。

2.示例代码

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

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Main{
    private static Logger log = Logger.getLogger(DomUtil.class);
    
    
    private static TransformerFactory transFact = TransformerFactory
            .newInstance();
    public static void saveDomToFile(Node doc, File file)
            throws IOException {
        String b = domToString(doc, true);
        FileUtil.writeToFile(file, b, "UTF-8");
    }
    public static String domToString(Document doc,
            boolean withXmlDeclaration) {
        return domToString(doc.getDocumentElement(), withXmlDeclaration);
    }
    
    public static String domToString(Node doc, boolean withXmlDeclaration) {
        try {
            
            Transformer transformer = transFact.newTransformer();
            if (!withXmlDeclaration)
                transformer.setOutputProperty(
                        OutputKeys.OMIT_XML_DECLARATION, "yes");
            DOMSource source = new DOMSource(doc);
            StringWriter output = new StringWriter();
            StreamResult result = new StreamResult(output);
            transformer.transform(source, result);
            return output.toString();
        } catch (TransformerConfigurationException tce) {
            
            Throwable x = tce;
            if (tce.getException() != null)
                x = tce.getException();
            x.printStackTrace();
            log.error(x);
        } catch (TransformerException te) {
            
            Throwable x = te;
            if (te.getException() != null)
                x = te.getException();
            x.printStackTrace();
            log.error(x);
        }
        return null;
    }
}

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