繁体   English   中英

如何获得在Java中标识节点的XPath表达式?

[英]How can I get an XPath expression that identifies a node in Java?

我有一个具有以下结构的XML文档:

<root>
    <a>
        <bd>
            <cd>
                <aa/>
                <bb/>
                <aa/>
            </cd>
        </bd>
    </a>
    <a>
        <bd>
            <cd>
                <aa/>
                <bb/>
                <aa/>
            </cd>
        </bd>
    </a>
    <tt>
        <at/>
        <bt/>
    </tt>
</root>

我正在使用将节点对象作为参数的递归函数。 我想在索引的XPath表达式中获取每个节点的xpath,例如root/a[1]/bd[0]/aa[2] 我正在使用DOM解析器,并从另一个递归函数调用此函数。

private static String getXPath(Node test_tempNode) {
    if (test_tempNode == null
            || test_tempNode.getNodeType() != Node.ELEMENT_NODE) {
        return "";
    }

    return getXPath(test_tempNode.getParentNode()) + "/"
            + test_tempNode.getNodeName();
}

您的代码似乎可以正常工作,只是不添加索引。 因此,我想您要做的就是在其父子列表中搜索当前节点的位置,并将其添加到xpath中。

private static String getXPath(Node test_tempNode) {
    if (test_tempNode == null
            || test_tempNode.getNodeType() != Node.ELEMENT_NODE) {
        return "";
    }

    //find index of the test_tempNode node in parent "list"
    Node parent = test_tempNode.getParentNode();
    NodeList childNodes = parent.getChildNodes();
    int index = 0;
    int found = 0;
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node current = childNodes.item(i);
        if (current.getNodeName().equals(test_tempNode.getNodeName())) {
            if (current == test_tempNode) {
                found = index;
            }
            index++;
        }
    }

    String strIdx = "[" + found + "]";
    if(index == 1){
        strIdx = "";
    }
    return getXPath(test_tempNode.getParentNode()) + "/"
            + test_tempNode.getNodeName() + strIdx;
}

这应该为每个节点打印出唯一的路径,并根据需要添加索引。

private void printXPaths(Node node, OutputStream stream, String current, Map<String, int> occurences)
{
    if (node.getNodeType() != Node.ELEMENT_NODE) {
        return;
    }
    String nodePath = current + "/" + node.getNodeName();
    if(occurences.contains(nodePath)) {
        int occurrencesCount = occurences[nodePath];
        nodePath += "[" + occurrencesCount + "]";
        occurences[nodePath] = occurrencesCount + 1;
    } else {
        occurences[nodePath] = 1;
    }

    stream.println(nodePath);
    NodeList children = node.getChildNodes();
    for(int i=0; i<children.getLength(); i++) {
        printXPaths(children.item(i), stream, nodePath, occurences);
    }
}

public void printXPaths(Document doc, OutputStream stream) {
    printXPaths(doc.getDocumentElement(), stream, "", new HashMap<String, int>());
}

这样,第一个指示将显示/ root / tag,而第二个指示将显示/ root / tag [1],依此类推。 希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM