Java 怎么通过xpath从父元素中选择元素

2019年7月29日20:56:30Java 怎么通过xpath从父元素中选择元素已关闭评论 467 715字阅读2分23秒

1.简介

Java 怎么通过xpath从父元素中选择元素?——请看下文。

2.示例代码

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


import org.w3c.dom.*;

import javax.xml.xpath.*;
import java.util.*;

public class Main {
    public static List<Element> SelectElements(Element parent,
            String expression) {
        List<Element> nodes = new ArrayList<Element>();
        XPath xpath = getXPath();
        try {
            XPathExpression xpathExpression = xpath.compile(expression);
            NodeList nodeList = (NodeList) xpathExpression.evaluate(parent,
                    XPathConstants.NODESET);
            for (int i = 0; i < nodeList.getLength(); i++) {
                nodes.add((Element) (nodeList.item(i)));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return nodes;
    }

    public static XPath getXPath() {
        return getXPathFactory().newXPath();
    }

    public static XPathFactory getXPathFactory() {
        return XPathFactory.newInstance();
    }
}

 
编程十万个怎么办