Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.File;

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.OutputKeys;

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 {
    private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();

    public static String prettyPrint(File file) {
        Transformer tf;
        try {
            tf = TransformerFactory.newInstance().newTransformer();
            tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            StreamResult stringResult = new StreamResult(new StringWriter());
            tf.transform(new DOMSource(convertFileToDom(file)), stringResult);
            return stringResult.getWriter().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void prettyPrint(Document document) {
        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer serializer;
        try {
            serializer = tfactory.newTransformer();
            // Setup indenting to "pretty print"
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            serializer.transform(new DOMSource(document), new StreamResult(System.out));
        } catch (TransformerException e) {
            // this is fatal, just dump the stack and throw a runtime exception
            e.printStackTrace();

            throw new RuntimeException(e);
        }
    }

    public static Document convertFileToDom(File xmlFile) {
        Document document;
        try {
            document = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder().parse(xmlFile);
        } catch (Exception e) {
            throw new IllegalStateException("Incoming file is not valid xml", e);
        }
        return document;
    }
}