save XML Document to a File - Java XML

Java examples for XML:DOM Document

Description

save XML Document to a File

Demo Code


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

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 java.io.*;

public class Main {

    public static void saveXML(File file, Document doc)
            throws TransformerException, IOException {
        DOMSource domSource = new DOMSource(doc);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;//from w w w.  jav a2s.c o m
        transformer = tf.newTransformer();
        //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(
                "{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(domSource,
                new StreamResult(new OutputStreamWriter(
                        new FileOutputStream(file), "UTF-8")));
        //transformer.transform(domSource, new StreamResult(new FileWriter(file)));
    }
}

Related Tutorials