Java examples for XML:DOM Document
create XML Document from XML Path
//package com.java2s; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; 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 main(String[] argv) throws Exception { String path = "java2s.com"; createXMLDocument(path);/* www .j av a 2 s. co m*/ } public static void createXMLDocument(String path) { createXMLDocument(path, "root"); } public static void createXMLDocument(String path, String root) { createXMLDocument(new File(path), root); } public static void createXMLDocument(File file) { createXMLDocument(file, "root"); } public static void createXMLDocument(File file, String rootName) { if (!file.exists()) { try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element root = document.createElement(rootName); document.appendChild(root); saveXMLDocument(document, file); } catch (Exception ex) { } } } public static void saveXMLDocument(Document document, String path) { saveXMLDocument(document, new File(path)); } public static void saveXMLDocument(Document document, File file) { FileOutputStream output = null; try { output = new FileOutputStream(file); Source source = new DOMSource(document); Result result = new StreamResult(output); Transformer transformer = TransformerFactory.newInstance() .newTransformer(); transformer.transform(source, result); } catch (Exception ex) { try { output.close(); } catch (IOException io) { } } finally { try { output.close(); } catch (IOException io) { } } } }