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 org.w3c.dom.Document;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class Main {
    /**
     * Converts a dom document to an xml String.
     * 
     * @param document
     * @return
     * @see XMLSerializer
     */
    public static String toXML(final Document document) {
        final XMLSerializer xmlSerializer = new XMLSerializer();

        final OutputFormat outputFormat = new OutputFormat(document);
        outputFormat.setOmitXMLDeclaration(false);
        outputFormat.setEncoding("UTF-8");
        outputFormat.setIndenting(true);

        final StringWriter stringWriter = new StringWriter();
        xmlSerializer.setOutputCharStream(stringWriter);
        xmlSerializer.setOutputFormat(outputFormat);
        try {
            xmlSerializer.serialize(document);
            stringWriter.flush();
            stringWriter.close();
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }

        return stringWriter.toString();
    }
}