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 javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class Main {
    public static String formatDocumentAsString(Document document) throws TransformerException {
        Writer out = new StringWriter();
        formatDocument(document, out);
        String formattedXML = out.toString();
        return formattedXML;
    }

    public static void formatDocument(Document document, Writer out) throws TransformerException {
        formatDocument(document, out, "UTF-8");
    }

    public static void formatDocument(Document document, Writer out, String encoding) throws TransformerException {
        document.normalizeDocument();
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer idTransform = transFactory.newTransformer();
        idTransform.setOutputProperty(OutputKeys.METHOD, "xml");
        idTransform.setOutputProperty(OutputKeys.INDENT, "yes");
        if (encoding != null) {
            idTransform.setOutputProperty(OutputKeys.ENCODING, encoding);
        }
        idTransform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        Source source = new DOMSource(document);
        Result result = new StreamResult(out);
        idTransform.transform(source, result);
    }
}