output and transform XML data in a file - Java XML

Java examples for XML:XML Transform

Description

output and transform XML data in a file

Demo Code


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

import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;

public class Main {
    /**//from   ww w  .  j  a v a 2s  .  c om
     * output XML data in a file
     *
     * @param doc
     * @param path
     */
    public static void buildXmlFile(Document doc, String path) {
        TransformerFactory tfactory = TransformerFactory.newInstance();
        try {
            Transformer transformer = tfactory.newTransformer();
            DOMSource source = new DOMSource(doc);

            StreamResult result = new StreamResult(new File(path));
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("encoding", "UTF-8");
            transformer.transform(source, result);

        } catch (TransformerConfigurationException e) {
            //TODO
        } catch (TransformerException e) {

        }
    }
}

Related Tutorials