Java 怎么从XML记录的文件表示形式创建DOM

2019年7月29日19:35:49Java 怎么从XML记录的文件表示形式创建DOM已关闭评论 497 1682字阅读5分36秒

1.简介

Java 怎么从XML记录的文件表示形式创建DOM?——请看下文。

2.示例代码

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

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Main{
    
    public static Document parseDomFromFile(File doc)
            throws org.xml.sax.SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        try {
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            return builder.parse(new org.xml.sax.InputSource(
                    new FileReader(doc)));
        } catch (javax.xml.parsers.ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
    }
    
    public static Document parseDomFromFile(File doc, String encoding)
            throws org.xml.sax.SAXException {
        return parseDomFromFile(doc, encoding, false);
    }
    
    public static Document parseDomFromFile(File doc, String encoding,
            boolean namespaceAware) throws org.xml.sax.SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        factory.setNamespaceAware(namespaceAware);
        try {
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            return builder.parse(new org.xml.sax.InputSource(
                    new StringReader(FileUtil.readFileToString(doc,
                            encoding))));
        } catch (javax.xml.parsers.ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
    }
}

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