Here you can find the source of writeToString(Node node)
Parameter | Description |
---|---|
node | a DOM node |
public static String writeToString(Node node)
//package com.java2s; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Node; 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 { private static DOMImplementation impl; private static DOMImplementationRegistry registry; /**/*w ww .j a v a 2 s .c o m*/ * Returns a string representation of the given node. Like {@link #parseDocument(String)}, we * use an intermediary byte array output stream so we can specify the encoding. * * @param node * a DOM node */ public static String writeToString(Node node) { ByteArrayOutputStream os = new ByteArrayOutputStream(); writeDocument(os, node); return os.toString(); } /** * Writes the given node to the given output stream. * * @param os * an output stream * @param node * a DOM node */ public static void writeDocument(OutputStream os, Node node) { getImplementation(); DOMImplementationLS implLS = (DOMImplementationLS) impl; // serialize to XML LSOutput output = implLS.createLSOutput(); output.setByteStream(os); // serialize the document, close the stream LSSerializer serializer = implLS.createLSSerializer(); serializer.getDomConfig().setParameter("format-pretty-print", true); serializer.write(node, output); } /** * Creates a new instance of the DOM registry and get an implementation of DOM 3 with Load Save * objects. */ private static void getImplementation() { try { if (registry == null) { registry = DOMImplementationRegistry.newInstance(); } if (impl == null) { impl = registry.getDOMImplementation("Core 3.0 XML 3.0 LS"); if (impl == null) { throw new RuntimeException("no DOM 3 implementation found"); } } } catch (ClassNotFoundException e) { throw new RuntimeException("DOM error", e); } catch (InstantiationException e) { throw new RuntimeException("DOM error", e); } catch (IllegalAccessException e) { throw new RuntimeException("DOM error", e); } } }