Java 怎么将XML文档(Document)写入OutputStream

2019年7月29日19:32:01Java 怎么将XML文档(Document)写入OutputStream已关闭评论 369 1337字阅读4分27秒

1.简介

Java 怎么将XML文档(Document)写入OutputStream?——请看下文。

2.示例代码

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

import java.io.OutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;

public class Main{
    public static void writeToStream(Document aDoc, OutputStream aOut) {
        DOMImplementationRegistry registry = getDOMImplementationRegistry();

        final DOMImplementationLS impl = (DOMImplementationLS) registry
                .getDOMImplementation("LS");
        final LSSerializer writer = impl.createLSSerializer();

        writer.getDomConfig().setParameter("format-pretty-print",
                Boolean.TRUE);

        LSOutput output = impl.createLSOutput();
        output.setEncoding("UTF-8");

        output.setByteStream(aOut);
        writer.write(aDoc, output);

    }
    protected static DOMImplementationRegistry getDOMImplementationRegistry() {
        try {
            return DOMImplementationRegistry.newInstance();
        } catch (ClassNotFoundException e) {
            throw new XmlException("DomImplementaion problem");
        } catch (InstantiationException e) {
            throw new XmlException("DomImplementaion problem");
        } catch (IllegalAccessException e) {
            throw new XmlException("DomImplementaion problem");
        }
    }
}

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