Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.IOException;

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class Main {
    /**
     * Convert xml to string.
     *
     * @param pDocument
     *            the p document
     * @param encoding
     *            the encoding
     * @return the string
     * @throws Exception
     *             the exception
     */
    public static String convertXML2String(Document pDocument, String encoding) throws Exception {
        TransformerFactory transformerFactory = null;
        Transformer transformer = null;
        DOMSource domSource = null;
        StringWriter writer = new java.io.StringWriter();
        StreamResult result = null;

        try {
            transformerFactory = TransformerFactory.newInstance();
            if (transformerFactory == null) {
                throw new Exception("TransformerFactory error");
            }

            transformer = transformerFactory.newTransformer();
            if (transformer == null) {
                throw new Exception("Transformer error");
            }

            if (encoding != null) {
                transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
            } else {
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            }

            domSource = new DOMSource(pDocument);
            result = new StreamResult(writer);

            transformer.transform(domSource, result);

            return writer.toString();
        } catch (TransformerFactoryConfigurationError e) {
            throw new Exception("TransformerFactoryConfigurationError", e);
        } catch (TransformerConfigurationException e) {
            throw new Exception("TransformerConfigurationException", e);
        } catch (TransformerException e) {
            throw new Exception("TransformerException", e);
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException ex) {
                throw new Exception("IO error", ex);
            }
        }
    }
}