Java 怎么基于xpath返回一个元素

2019年7月29日20:56:03Java 怎么基于xpath返回一个元素已关闭评论 389 709字阅读2分21秒

1.简介

Java 怎么基于xpath返回一个元素?——请看下文。

2.示例代码

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



import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

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

import org.w3c.dom.NodeList;

public class Main {
    
    static Element getElementByAttribute(Document doc, String xPath) {
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = null;
        NodeList nl = null;
        try {
            expr = xpath.compile(xPath);
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return (Element) nl.item(0);
    }
}

 
编程十万个怎么办