Java 怎么根据xpath查找节点

2019年7月29日20:52:07Java 怎么根据xpath查找节点已关闭评论 565 897字阅读2分59秒

1.简介

Java 怎么根据xpath查找节点?——请看下文。

2.示例代码

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



import java.util.StringTokenizer;

import org.w3c.dom.Node;

public class Main {
    public static Node findNodeByXPath(Node base, String xpath) {
        if ("/".equals(xpath)) {
            return base;
        }
        Node node = base;
        StringTokenizer tok = new StringTokenizer(xpath, "/");
        while (tok.hasMoreTokens()) {
            String subpath = tok.nextToken();
            String localName;
            int nodePos = 0;
            int index = subpath.indexOf('[');
            if (index > 0) {
                localName = subpath.substring(0, index).toLowerCase();
                nodePos = Integer.parseInt(subpath.substring(index + 1,
                        subpath.indexOf(']')));
            } else {
                localName = subpath.toLowerCase();
            }
            short nodeType = Node.ELEMENT_NODE;
            if ("text()".equals(localName)) {
                nodeType = Node.TEXT_NODE;
                localName = "";
            }
            node = node.getFirstChild();
            int pos = 0;
            while (node != null) {
                if (node.getNodeType() == nodeType
                        && localName.equals(node.getLocalName()
                                .toLowerCase())) {
                    if (pos == nodePos) {
                        break;
                    }
                    ++pos;
                }
                node = node.getNextSibling();
            }
        }
        return node;
        

    }
}

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