Java XML Document to File writeToFile(File file, Document doc)

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

Description

write To File

License

Open Source License

Declaration

public static void writeToFile(File file, Document doc) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

import java.io.StringWriter;

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 org.w3c.dom.Element;

public class Main {
    public static void writeToFile(File file, Document doc) throws Exception {
        String xmlString = getXMLAsString(doc);
        try (FileOutputStream os = new FileOutputStream(file)) {
            byte[] xmlStringContent = xmlString.getBytes("UTF-8");
            os.write(xmlStringContent);/*from  www  .j  av  a2s.  c o  m*/
            os.close();
        }
    }

    public static String getXMLAsString(Document doc) throws Exception {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);

        return result.getWriter().toString();
    }

    public static String getXMLAsString(Element eElement) throws Exception {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(eElement);
        transformer.transform(source, result);

        return result.getWriter().toString();
    }
}

Related

  1. writeDomToFile(String filename, Document document)
  2. writeFile(String fileName, Document content)
  3. writeTo(Document document, File output)
  4. writeToFile(Document doc, String file)
  5. writeToFile(Document doc, String filePath)
  6. writeXML(Document doc, File file)
  7. writeXml(Document doc, File output)
  8. writeXml(Document doc, File outputFile)
  9. writeXML(Document doc, String fileName)