Here you can find the source of writeDocument(Document doc, String filePath)
Parameter | Description |
---|---|
doc | object representing XML file to be written |
filePath | path to which the file is to be written |
Parameter | Description |
---|---|
IOException | Occurs if there is a problem writing to thefilesystem. |
public static void writeDocument(Document doc, String filePath) throws IOException
//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(); } }