Java XML Document to File writeXmlFile(String fileName, Document document)

Here you can find the source of writeXmlFile(String fileName, Document document)

Description

Writes XML Document into an xml file.

License

Open Source License

Parameter

Parameter Description
fileName the target file with the full path
document the source document

Exception

Parameter Description
Exception an exception

Return

boolean true if the file saved

Declaration

public static boolean writeXmlFile(String fileName, Document document) throws Exception 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2015 CA.  All rights reserved.
 *
 * This source file is licensed under the terms of the Eclipse Public License 1.0
 * For the full text of the EPL please see https://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

import javax.xml.XMLConstants;

import javax.xml.transform.OutputKeys;
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;

import java.io.File;

public class Main {
    /**/* w  w  w  .  j  av  a 2  s. c  o  m*/
     * Writes  XML Document into an xml file.
     * 
     * @param fileName  the target file with the full path
     * @param document   the source document
     * @return   boolean true if the file saved
     * @throws Exception
     */
    public static boolean writeXmlFile(String fileName, Document document) throws Exception {

        // creating and writing to xml file  

        File file = new File(fileName);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); // to prevent XML External Entities attack

        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(new DOMSource(document), new StreamResult(file));

        return true;

    }
}

Related

  1. writeXmlFile(Document doc, String filename)
  2. writeXmlFile(Document doc, String filename)
  3. writeXmlFile(Document doc, String filename)
  4. writeXMLFile(Document document, Writer writer)
  5. writeXmlFile(File file, Document document)
  6. WriteXMLFile2(Document doc, String strFilePath)
  7. writeXmlToStream(Document doc, OutputStream stream)
  8. writeXMLtoStream(Object osw, Document doc)