gpt4 book ai didi

java - 如何获得标识 Java 节点的 XPath 表达式?

转载 作者:行者123 更新时间:2023-11-30 11:18:15 25 4
gpt4 key购买 nike

我有一个具有以下结构的 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;
}

关于java - 如何获得标识 Java 节点的 XPath 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23934725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com