Java 怎么将DOM文档(Document)序列化为输出流(OutputStream)

2019年7月29日19:19:21Java 怎么将DOM文档(Document)序列化为输出流(OutputStream)已关闭评论 1,732 822字阅读2分44秒

1.简介

Java 怎么将DOM文档(Document)序列化为输出流(OutputStream)?——请看下文。

2.示例代码

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


import java.io.OutputStream;

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 {
    
    public static void serializeDocument(Document document, OutputStream os) {
        try {
            
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(os);
            transformer.transform(source, result);
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}

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