Java XML Document to File writeDoc(Document doc, File aFile)

Here you can find the source of writeDoc(Document doc, File aFile)

Description

if aFile is given, will write to file, otherwise return as String

License

Creative Commons License

Declaration

public static String writeDoc(Document doc, File aFile) 

Method Source Code

//package com.java2s;
//License from project: Creative Commons License 

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

import org.w3c.dom.Document;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class Main {
    /** if aFile is given, will write to file, otherwise return as String */
    public static String writeDoc(Document doc, File aFile) {
        String s = null;//from  www .  j  ava 2  s . c o m
        try {
            OutputFormat format = new OutputFormat("XML", "UTF-8", true);
            if (aFile != null) {
                FileOutputStream out = new FileOutputStream(aFile);
                XMLSerializer serializer = new XMLSerializer(out, format);
                serializer.serialize(doc);
                out.close();
                out.flush();
            } else {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                XMLSerializer serializer = new XMLSerializer(out, format);
                serializer.serialize(doc);
                out.close();
                out.flush();
                s = out.toString();
            }
        } catch (Exception e) {
            throw new RuntimeException(
                    "Exception while writing new XML document: \n", e);
        }
        return s;
    }
}

Related

  1. storeXML(Document doc, File file)
  2. storeXml(final File xmlFile, final Document document)
  3. write(Document doc, File out)
  4. write(final Document doc, final File file)
  5. writeDataToFile(File file, Document doc)
  6. writeDoc(Document doc, File file)
  7. writeDocToFile(Document doc, String filename)
  8. writeDocToFile(Document doc, String fileName)
  9. writeDocument(Document doc, String filename)