Java 怎么根据名称获取XML值

2019年7月29日19:37:13Java 怎么根据名称获取XML值已关闭评论 410 1129字阅读3分45秒

1.简介

Java 怎么根据名称获取XML值?——请看下文。

2.示例代码

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


import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

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

    public static String getXMLValueByName(String xmlFilePath, String name) {
        String returnValue = "No Value!";
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                .newInstance();
        try {
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            InputStream is = new FileInputStream(xmlFilePath);
            Document doc = builder.parse(is);
            Element root = doc.getDocumentElement();
            NodeList nodes = root.getChildNodes();
            if (nodes != null) {
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        String test = node.getNodeName();
                        if (test.equals(name)) {
                            returnValue = node.getTextContent().trim();
                        }
                    }
                }
            }
        } catch (Exception e) {

        }
        return returnValue;
    }
}

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