Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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);
        }
        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;
    }
}