Java XML String Transform writeElement(Element element, String fileName)

Here you can find the source of writeElement(Element element, String fileName)

Description

Writes an element out to a file.

License

LGPL

Parameter

Parameter Description
element The XML element to write out.
fileName The file name to write to. Existing file is overwriten.

Declaration

public static void writeElement(Element element, String fileName) 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import org.w3c.dom.*;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.*;

public class Main {
    /**/*from  w  ww . jav a2s .  c  o m*/
     * Writes an element out to a file.
     * @param element The XML element to write out.
     * @param fileName The file name to write to. Existing file is overwriten.
     */
    public static void writeElement(Element element, String fileName) {
        File file = new File(fileName);
        file.delete();
        DOMSource domSource = new DOMSource(element);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            StreamResult result = new StreamResult(fos);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.transform(domSource, result);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            throw new RuntimeException("Failed to write XML element to:" + fileName, e);
        } finally {
            try {
                fos.flush();
            } catch (Exception e) {
            }
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }
}

Related

  1. toLCCNDisplay(String packedLCCN)
  2. tomcatPort(String fileName)
  3. toString(Collection c, String separator)
  4. toString(Source input)
  5. write(Node node, OutputStream out, String... props)
  6. writeNodeSubtreeXMLString(final Node node, final Writer writer)
  7. writePropToString(Properties props)
  8. writeResultToFile(final StreamResult result, final String path)
  9. writeToFile(String xmlContent, String path)