Java 怎么通过xpath表达式从xml节点获取元素列表

2019年7月29日20:55:53Java 怎么通过xpath表达式从xml节点获取元素列表已关闭评论 459 767字阅读2分33秒

1.简介

Java 怎么通过xpath表达式从xml节点获取元素列表?——请看下文。

2.示例代码

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


import java.util.LinkedList;
import java.util.List;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    static private XPath xpath;

    static public List<Element> elements(Node context, String expression) {
        try {
            NodeList nodeList = (NodeList) xpath.evaluate(expression,
                    context, XPathConstants.NODESET);
            List<Element> result = new LinkedList<Element>();
            for (int i = 0, len = nodeList.getLength(); i < len; i++) {
                result.add((Element) nodeList.item(i));
            }
            return result;
        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
            throw new RuntimeException("invalid xpath expresion used");
        }
    }
}

 
编程十万个怎么办