Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

import java.io.StringWriter;

import java.util.Properties;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

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

public class Main {
    /**
     * Converts a dom to a String
     *
     * @param dom dom to convert
     * @return the dom as a String
     */
    public static String writeDomToString(Document dom) {
        return writeDomToString(dom, null);
    }

    /**
     * Converts a dom to a String
     *
     * @param dom dom to convert
     * @param outputProperties the properties for the String representation of
     * the XML
     * @return the dom as a String
     */
    public static String writeDomToString(Document dom, Properties outputProperties) {
        try {
            StringWriter ret = new StringWriter();
            TransformerFactory transFact = TransformerFactory.newInstance();
            // transFact.setAttribute("indent-number", 2);
            Transformer transformer = transFact.newTransformer();
            if (outputProperties != null) {
                transformer.setOutputProperties(outputProperties);
            }
            DOMSource source = new DOMSource(dom);
            StreamResult result = new StreamResult(ret);
            transformer.transform(source, result);
            return ret.toString();
        } catch (Exception e) {
            throw new RuntimeException("Could not write dom to string!", e);
        }
    }

    /**
     * Converts a dom element to a String
     *
     * @param node
     * @return the dom as a String
     */
    public static String writeDomToString(Element node) {
        DOMImplementation domImplementation = node.getOwnerDocument().getImplementation();
        if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) {
            DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation.getFeature("LS",
                    "3.0");
            LSSerializer lsSerializer = domImplementationLS.createLSSerializer();

            LSOutput lsOutput = domImplementationLS.createLSOutput();
            lsOutput.setEncoding("UTF-8");

            StringWriter stringWriter = new StringWriter();
            lsOutput.setCharacterStream(stringWriter);
            lsSerializer.write(node, lsOutput);
            return stringWriter.toString();
        } else {
            throw new RuntimeException("DOM 3.0 LS and/or DOM 2.0 Core not supported.");
        }
    }
}