Java XML Document Serialize serialize(Document document, boolean prettyPrint)

Here you can find the source of serialize(Document document, boolean prettyPrint)

Description

serialize

License

Apache License

Declaration

public static String serialize(Document document, boolean prettyPrint) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.StringWriter;
import java.io.Writer;
import org.w3c.dom.DOMConfiguration;

import org.w3c.dom.DOMImplementation;
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 {
    private static DOMImplementation IMPL;

    public static String serialize(Document document, boolean prettyPrint) {
        DOMImplementationLS impl = getDOMImpl();
        LSSerializer serializer = impl.createLSSerializer();
        // document.normalizeDocument();
        DOMConfiguration config = serializer.getDomConfig();
        if (prettyPrint && config.canSetParameter("format-pretty-print", Boolean.TRUE)) {
            config.setParameter("format-pretty-print", true);
        }/*w ww  . ja  v a  2  s  .co m*/
        config.setParameter("xml-declaration", true);
        LSOutput output = impl.createLSOutput();
        output.setEncoding("UTF-8");
        Writer writer = new StringWriter();
        output.setCharacterStream(writer);
        serializer.write(document, output);
        return writer.toString();
    }

    @SuppressWarnings("unchecked")
    public synchronized static <T> T getDOMImpl() {
        if (IMPL == null) {
            try {
                DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
                IMPL = registry.getDOMImplementation("LS 3.0");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return (T) IMPL;
    }
}

Related

  1. serialiseDOM(Document doc, String filepath)
  2. serialize(Document d, File f)
  3. serialize(Document d, OutputStream out, URL transformerLocation, Map properties)
  4. serialize(Document doc)
  5. serialize(Document doc, Writer out)
  6. serialize(Document document, boolean prettyPrint)
  7. serialize(Document document, File targetFile)
  8. serialize(Document document, OutputStream ostream)
  9. serialize(Document document, OutputStream out)