Java XML Document Save to File saveXMLDocument(String fileName, Document doc)

Here you can find the source of saveXMLDocument(String fileName, Document doc)

Description

Save XML file and saves XML document.

License

Apache License

Parameter

Parameter Description
fileName a parameter
doc a parameter

Exception

Parameter Description
Exception object

Return

boolean

Declaration

public static boolean saveXMLDocument(String fileName, Document doc) throws Exception 

Method Source Code

//package com.java2s;
/**/*from  www.  j  a v  a  2s. c o  m*/
* Copyright Microsoft Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

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

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 {
    /**
     * Save XML file and saves XML document.
     *
     * @param fileName
     * @param doc
     * @return boolean
     * @throws Exception object
     */
    public static boolean saveXMLDocument(String fileName, Document doc) throws Exception {
        // open output stream where XML Document will be saved
        File xmlOutputFile = new File(fileName);
        FileOutputStream fos = null;
        Transformer transformer;
        try {
            fos = new FileOutputStream(xmlOutputFile);
            // Use a Transformer for output
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(fos);
            // transform source into result will do save
            transformer.transform(source, result);
        } finally {
            if (fos != null) {
                fos.close();
            }
        }

        return true;
    }
}

Related

  1. saveXml(Document doc, String filename)
  2. saveXML(Document document, String filename)
  3. saveXml(Document dom, String filePath)
  4. saveXml(Document modDoc, String path)
  5. saveXMLDocument(Document document, String path)
  6. saveXmlToStreamWriter(Document doc)