Java examples for XML:DOM Document
Write the XML-encoding of a Document Document to an java.io.OutputStream OutputStream .
/*/*from ww w. ja v a2 s.c o m*/ * Copyright 2006-2015 WebPKI.org (http://webpki.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ //package com.java2s; 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 { /** * Write the XML-encoding of a {@link Document Document} to an * {@link java.io.OutputStream OutputStream}. * @param d Document * @param out Stream * @throws IOException If anything unexpected happens... */ 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(); } }