Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import org.w3c.dom.Document;

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 java.io.OutputStream;
import java.io.StringWriter;

public class Main {
    public static String doc2str(Document doc) throws TransformerConfigurationException, TransformerException {
        StreamResult result = new StreamResult(new StringWriter());
        doc2stream(doc, result);
        String xmlString = result.getWriter().toString();
        return xmlString;
    }

    public static void doc2stream(Document doc, StreamResult result)
            throws TransformerConfigurationException, TransformerException {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
    }

    public static void doc2stream(Document doc, OutputStream out)
            throws TransformerConfigurationException, TransformerException {
        doc2stream(doc, new StreamResult(out));
    }
}