Java 怎么从XML文档、XML文件和XML字符串获取根(Root)

2019年7月29日19:27:33Java 怎么从XML文档、XML文件和XML字符串获取根(Root)已关闭评论 520 1200字阅读4分0秒

1.简介

Java 怎么从XML文档、XML文件和XML字符串获取根(Root)?——请看下文。

2.示例代码

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



import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

public class Main {
    public static void main(String[] argv) throws Exception {
        String path = "tah1986.com";
        System.out.println(getRoot(path));
    }

    public static Element getRoot(String path) {
        return getRoot(new File(path));
    }

    public static Element getRoot(File file) {
        return getRoot(loadXMLDocument(file));
    }

    public static Element getRoot(Document document) {
        return getRoot(document, "root");
    }

    public static Element getRoot(Document document, String root) {
        if (document == null) {
            throw new IllegalArgumentException("Null document");
        }

        NodeList nodeList = document.getElementsByTagName(root);
        return nodeList.item(0) != null ? (Element) nodeList.item(0) : null;
    }

    public static Document loadXMLDocument(String path) {
        return loadXMLDocument(new File(path));
    }

    public static Document loadXMLDocument(File file) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(file);
            return document;
        } catch (Exception ex) {
            return null;
        }
    }
}

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