Java 怎么将文档的XML编码写入java.io.outputstream outputstream

2019年7月29日19:11:27Java 怎么将文档的XML编码写入java.io.outputstream outputstream已关闭评论 729 1335字阅读4分27秒

1.简介

Java 怎么将文档的XML编码写入java.io.outputstream outputstream?——请看下文。

2.示例代码

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

 

import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import org.w3c.dom.Element;
import org.w3c.dom.Document;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;

public class Main {
    
    public static void writeXML(Document d, OutputStream out)
            throws IOException {
        DOMImplementationLS DOMiLS = (DOMImplementationLS) d
                .getImplementation();
        ;
        LSOutput LSO = DOMiLS.createLSOutput();
        LSO.setByteStream(out);
        LSSerializer LSS = DOMiLS.createLSSerializer();
        if (!LSS.write(d, LSO)) {
            throw new IOException("[Serialization failed!]");
        }
    }

    public static void writeXML(Element e, OutputStream out)
            throws IOException {
        DOMImplementationLS DOMiLS = (DOMImplementationLS) e
                .getOwnerDocument().getImplementation();
        ;
        LSOutput LSO = DOMiLS.createLSOutput();
        LSO.setByteStream(out);
        LSSerializer LSS = DOMiLS.createLSSerializer();
        if (!LSS.write(e, LSO)) {
            throw new IOException("[Serialization failed!]");
        }
    }

    public static byte[] writeXML(Document d) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        writeXML(d, baos);
        baos.close();
        return baos.toByteArray();
    }

    public static byte[] writeXML(Element e) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        writeXML(e, baos);
        baos.close();
        return baos.toByteArray();
    }
}

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