Java XML Document to File writeDocument(Document doc, String filePath)

Here you can find the source of writeDocument(Document doc, String filePath)

Description

Properly formats a DOM object and writes it to the filesystem.

License

Open Source License

Parameter

Parameter Description
doc object representing XML file to be written
filePath path to which the file is to be written

Exception

Parameter Description
IOException Occurs if there is a problem writing to thefilesystem.

Declaration

public static void writeDocument(Document doc, String filePath) throws IOException 

Method Source Code

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

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import java.io.StringWriter;

import java.io.Writer;
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 {
    /**//from   w w w .j  av  a  2  s .  c o  m
     * Properly formats a DOM object and writes it to the filesystem.
     * 
     * @param doc object representing XML file to be written
     * @param filePath path to which the file is to be written
     * @throws IOException Occurs if there is a problem writing to the
     *             filesystem.
     */
    public static void writeDocument(Document doc, String filePath) throws IOException {
        // write the document to file
        OutputStream os;
        os = new FileOutputStream(filePath);
        os.write(format(doc).getBytes("US-ASCII"));
        os.close();
    }

    /**
     * formats XML with proper indentation
     * 
     * @param document represents the XML to be formatted
     * @return String of properly formatted XML text
     * @throws IOException thrown if formatting fails - usually due to an
     *             invalid object
     */
    public static String format(Document document) throws IOException {
        OutputFormat format = new OutputFormat(document);
        format.setLineWidth(65);
        format.setIndenting(true);
        format.setIndent(2);
        Writer out = new StringWriter();
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(document);

        return out.toString();
    }
}

Related

  1. writeDoc(Document doc, File file)
  2. writeDocToFile(Document doc, String filename)
  3. writeDocToFile(Document doc, String fileName)
  4. writeDocument(Document doc, String filename)
  5. writeDocument(Document doc, String filePath)
  6. writeDocument(Document document, File file)
  7. writeDocument(Document document, File file)
  8. writeDocument(Document document, String path)
  9. writeDocumentTo(Document doc, File file)