Java XML Document to File writeDocument(Document document, String path)

Here you can find the source of writeDocument(Document document, String path)

Description

write Document

License

Open Source License

Declaration

public static void writeDocument(Document document, String path)
            throws Exception 

Method Source Code

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

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

import java.io.PrintWriter;

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;

public class Main {
    public static void writeDocument(Document document, String path)
            throws Exception {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        File file = new File(path);
        if (!file.exists()) {
            File parent = file.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();//from w  w  w  .  j  a v a 2 s.c o  m
            }
        }

        PrintWriter writer = new PrintWriter(new FileOutputStream(path));
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
    }
}

Related

  1. writeDocument(Document doc, String filename)
  2. writeDocument(Document doc, String filePath)
  3. writeDocument(Document doc, String filePath)
  4. writeDocument(Document document, File file)
  5. writeDocument(Document document, File file)
  6. writeDocumentTo(Document doc, File file)
  7. writeDocumentToFile(Document document, String filePathname, String method, int indent)
  8. writeDOM2XMLFile(Document domDoc, String fileName)
  9. writeDOMDocumentToFile(Document doc, String filePath)