save XML Document to a File - Android XML

Android examples for XML:XML Document

Description

save XML Document to a File

Demo Code


//package com.java2s;

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

import javax.xml.transform.Result;
import javax.xml.transform.Source;
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;

public class Main {
    public static void saveXMLDocument(Document document, String path) {
        saveXMLDocument(document, new File(path));
    }/*from  ww  w  . j av a  2 s . c om*/

    public static void saveXMLDocument(Document document, File file) {
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(file);
            Source source = new DOMSource(document);
            Result result = new StreamResult(output);
            Transformer transformer = TransformerFactory.newInstance()
                    .newTransformer();
            transformer.transform(source, result);
        } catch (Exception ex) {
            try {
                output.close();
            } catch (IOException io) {
            }
        } finally {
            try {
                output.close();
            } catch (IOException io) {
            }
        }
    }
}

Related Tutorials