Here you can find the source of writeXmlFile(Document doc, String filename)
Parameter | Description |
---|---|
doc | DOM document |
filename | target file name |
Parameter | Description |
---|---|
Exception | an exception |
public static void writeXmlFile(Document doc, String filename) throws Exception
//package com.java2s; /*// w ww .j a v a 2s. c om * Copyright (c) 2010-2012 Research In Motion Limited. All rights reserved. * * This program and the accompanying materials are made available * under the terms of the Eclipse Public License, Version 1.0, * which accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v10.html * */ import java.io.File; import java.io.FileOutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; 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 { /** * Write DOM to a file * * @param doc * DOM document * @param filename * target file name * @throws Exception */ public static void writeXmlFile(Document doc, String filename) throws Exception { writeXmlFile(doc, filename, "ISO-8859-1", "no"); } /** * Write DOM to a file * * @param doc * DOM document * @param filename * target file name * @param encoding * specified encoding * @param omitXmlDeclaration * flag to indicate if xml declaration statement is included * @throws Exception */ public static void writeXmlFile(Document doc, String filename, String encoding, String omitXmlDeclaration) throws Exception { // Prepare the DOM document for writing Source source = new DOMSource(doc); // Prepare the output file FileOutputStream outputStream = new FileOutputStream(new File(filename)); Result result = new StreamResult(outputStream); // Write the DOM document to the file Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, encoding); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDeclaration); transformer.transform(source, result); outputStream.flush(); outputStream.close(); } }