Java 怎么通过xpath表达式从XML字符串中选择节点

2019年7月29日20:55:59Java 怎么通过xpath表达式从XML字符串中选择节点已关闭评论 350 737字阅读2分27秒

1.简介

Java 怎么通过xpath表达式从XML字符串中选择节点?——请看下文。

2.示例代码

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

 

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

import org.w3c.dom.NodeList;

public class Main {
    public static void main(String[] argv) throws Exception {
        String express = "tah1986.com";
        Object source = "tah1986.com";
        System.out.println(selectNodes(express, source));
    }

    public static NodeList selectNodes(String express, Object source) {
        NodeList result = null;
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        try {
            result = (NodeList) xpath.evaluate(express, source,
                    XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }

        return result;
    }
}

 
编程十万个怎么办