Java 怎么在特定节点上执行xpath查询

2019年7月29日20:55:31Java 怎么在特定节点上执行xpath查询已关闭评论 335 621字阅读2分4秒

1.简介

Java 怎么在特定节点上执行xpath查询?——请看下文。

2.示例代码

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



import javax.xml.namespace.QName;

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

import org.w3c.dom.Node;

public class Main {
    
     
    @SuppressWarnings("unchecked")
    public static <T> T xpath(Node doc, String xpath_expr, QName type) {
        XPathFactory xpathfactory = XPathFactory.newInstance();
        XPath xpath = xpathfactory.newXPath();
        XPathExpression expr;
        try {
            expr = xpath.compile(xpath_expr);
            return (T) expr.evaluate(doc, type);
        } catch (XPathExpressionException e) {
            throw new RuntimeException(e);
        }
    }
}

 
编程十万个怎么办