Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class Main {
    public static String docToString(Document doc) {
        return docToString(doc, false);
    }

    public static String docToString(Document doc, boolean formated) {

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = null;
        try {
            transformer = tf.newTransformer();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
            return null;
        }

        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        if (formated) {
            // linefeed formatting
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        } else {
            // remove xml header
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
        StringWriter sw = new StringWriter();
        StreamResult sr = new StreamResult(sw);

        DOMSource domSource = new DOMSource(doc);
        try {
            transformer.transform(domSource, sr);
        } catch (TransformerException e) {
            e.printStackTrace();
            return null;
        }
        return sw.toString();
    }
}