Java 怎么从xpath获取唯一节点

2019年7月29日20:55:25Java 怎么从xpath获取唯一节点已关闭评论 371 1060字阅读3分32秒

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.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static Node getUniqueNode(Node node, String xPathAsString)
            throws XPathExpressionException {
        NodeList nodeList = getNodeList(node, xPathAsString);
        return nodeList == null || nodeList.getLength() == 0 ? null
                : nodeList.item(0);
    }

    public static NodeList getNodeList(Document doc, String xPathAsString)
            throws XPathExpressionException {
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xpath.compile(xPathAsString);
        return (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    }

    public static NodeList getNodeList(Node node, String xPathAsString)
            throws XPathExpressionException {
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xpath.compile(xPathAsString);
        return (NodeList) expr.evaluate(node, XPathConstants.NODESET);
    }
}

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