Java 怎么根据名称获取XML节点属性

2019年7月21日19:46:21Java 怎么根据名称获取XML节点属性已关闭评论 400 1287字阅读4分17秒

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 nodeName = "tah1986.com";
        String attributeName = "tah1986.com";
        System.out.println(getNodeAttributeByName(xmlFilePath, nodeName,
                attributeName));
    }

    public static String getNodeAttributeByName(String xmlFilePath,
            String nodeName, String attributeName) {
        String returnVal = "No value!";
        DocumentBuilderFactory domBuilderFactory = DocumentBuilderFactory
                .newInstance();
        try {

            DocumentBuilder domBuilder = domBuilderFactory
                    .newDocumentBuilder();
            InputStream is = new FileInputStream(xmlFilePath);
            Document doc = domBuilder.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(nodeName)) {
                            returnVal = node.getAttributes()
                                    .getNamedItem(attributeName)
                                    .getNodeValue();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnVal;
    }
}

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