Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.FileOutputStream;

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
    public static void writeToFile(File file, Document doc) throws Exception {
        String xmlString = getXMLAsString(doc);
        try (FileOutputStream os = new FileOutputStream(file)) {
            byte[] xmlStringContent = xmlString.getBytes("UTF-8");
            os.write(xmlStringContent);
            os.close();
        }
    }

    public static String getXMLAsString(Document doc) throws Exception {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);

        return result.getWriter().toString();
    }

    public static String getXMLAsString(Element eElement) throws Exception {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(eElement);
        transformer.transform(source, result);

        return result.getWriter().toString();
    }
}