Java 怎么从XML路径创建XML文档(Document)

2019年7月29日19:28:10Java 怎么从XML路径创建XML文档(Document)已关闭评论 411 1790字阅读5分58秒

1.简介

Java 怎么从XML路径创建XML文档(Document)?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



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 = "tah1986.com";
        createXMLDocument(path);
    }

    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) {
            }
        }
    }
}

 
继续阅读
编程十万个怎么办