Java 怎么从类路径(ClassPath)获取XML文档(Document)

2019年7月29日19:21:03Java 怎么从类路径(ClassPath)获取XML文档(Document)已关闭评论 392 997字阅读3分19秒

1.简介

Java 怎么从类路径(ClassPath)获取XML文档(Document)?——请看下文。

2.示例代码

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

import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

public class Main{
    public static void main(String[] argv) throws Exception{
        String resourceName = "tah1986.com";
        System.out.println(getDocumentFromClassPath(resourceName));
    }
    public static Document getDocumentFromClassPath(String resourceName) {
        return getDocumentFromClassPath(resourceName, true);
    }
    public static Document getDocumentFromClassPath(String resourceName,
            boolean namespaceAware) {
        return getDocumentFromStream(ResourceUtil.getStream(resourceName),
                namespaceAware);
    }
    public static Document getDocumentFromStream(InputStream is,
            boolean namespaceAware) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory
                    .newInstance();
            dbf.setNamespaceAware(namespaceAware);
            DocumentBuilder builder = dbf.newDocumentBuilder();
            Document ret = builder.parse(is);
            return ret;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

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