Java XML Document Save to File save(Document doc, File file)

Here you can find the source of save(Document doc, File file)

Description

save

License

LGPL

Declaration

public static void save(Document doc, File file) 

Method Source Code

//package com.java2s;
/**/*w w  w .  j  av  a2 s.  c om*/
 *  Copyright (C) 2008-2014  Telosys project org. ( http://www.telosys.org/ )
 *
 *  Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.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.gnu.org/licenses/lgpl.html
 *
 *  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 javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

public class Main {
    public static void save(Document doc, String fileName) {
        save(doc, new StreamResult(fileName));
    }

    public static void save(Document doc, File file) {
        save(doc, new StreamResult(file));
    }

    private static void save(Document doc, Result result) {
        //--- Write the XML document in XML file
        try {
            Source source = new DOMSource(doc);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();

            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            //--- Transform the DOM document into XML file 
            transformer.transform(source, result);
        } catch (TransformerException e) {
            throw new RuntimeException("XML error : Cannot save : TransformerException", e);
        } catch (TransformerFactoryConfigurationError e) {
            throw new RuntimeException("XML error : Cannot save : TransformerFactoryConfigurationError", e);
        }
    }
}

Related

  1. save(Document doc, String file, String encoding)
  2. save(Document document, OutputStream out, Properties outputProperties)
  3. save(Document document, OutputStream outputStream)
  4. save(Document document, String fileName)