Here you can find the source of WriteXMLFile2(Document doc, String strFilePath)
Document
in memory out to a standard XML file.
Parameter | Description |
---|---|
doc | the <code>Document</code> object for the XML file to list |
strFilePath | the XML file to write to |
Parameter | Description |
---|---|
custom | custom exception if file is not writeable |
ioe | IOException if an error occurs on file creation |
fnfe | FileNotFoundException if PrintWriter constructor fails |
public static void WriteXMLFile2(Document doc, String strFilePath) throws Exception
//package com.java2s; import com.sun.org.apache.xml.internal.serialize.OutputFormat; import com.sun.org.apache.xml.internal.serialize.XMLSerializer; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import org.w3c.dom.Document; public class Main { /** /* ww w . ja v a2s. c o m*/ * Write the <code>Document</code> in memory out to a standard XML file. * @param doc the <code>Document</code> object for the XML file to list * @param strFilePath the XML file to write to * @throws custom custom exception if file is not writeable * @throws ioe IOException if an error occurs on file creation * @throws fnfe FileNotFoundException if PrintWriter constructor fails */ public static void WriteXMLFile2(Document doc, String strFilePath) throws Exception { // open file for writing File file = new File(strFilePath); // ensure that file is writeable try { file.createNewFile(); if (!file.canWrite()) { throw new Exception("FileNotWriteable"); } } catch (IOException ioe) { throw ioe; } // create a PrintWriter to write the XML file to PrintWriter pw = null; try { pw = new PrintWriter(file); } catch (FileNotFoundException fnfe) { throw fnfe; } // write out the serialized form pw.print(getXMLListing(doc)); pw.close(); } /** Return a <code>String</code> containing an XML file in serialized form. * @param doc the <code>Document</code> object for the XML file to list * @return (<code>String</code>) the XML file in serialized form */ public static String getXMLListing(Document doc) { // make a serializable version of the XML Document object // reference: www-106.ibm.com/developerworks/xml/library/x-injava2/?dwzone=xml OutputFormat of = new OutputFormat(doc); of.setIndenting(true); // setIndenting must preceed setIndent of.setIndent(2); of.setLineSeparator(System.getProperty("line.separator")); // of.setPreserveSpace( true ) ; StringWriter sw = new StringWriter(); // use a StringWriter instead of serializing directly to the // ObjectOutputStream because serializing directly yields a // java.io.OptionalDataException when reading the data with // ObjectInputStream.readObject() XMLSerializer xmlser = new XMLSerializer(sw, of); try { xmlser.serialize(doc); } catch (IOException ioe) { return "<p>IOException Error in getXMLListing( Document ):<br/>" + " " + ioe.toString(); } return sw.toString(); } }