我已经写了我想要实现的目标.但是,getElementIdx()
功能不会返回正确的计数.有一个问题,getPreviousSibling()
但我不知道为什么.
public static String getElementXpath(DOMElement elt){
String path = "";
try{
for (; elt != null; elt = (DOMElement) elt.getParentNode()){
int idx = getElementIdx(elt);
String xname = elt.getTagName().toString();
if (idx >= 1) xname += "[" + idx + "]";
path = "/" + xname + path;
}
}catch(Exception ee){
}
return path;
}
public static int getElementIdx(DOMElement elt) {
int count = 1;
try{
for (DOMElement sib = (DOMElement) elt.getNextSibling(); sib != null; sib = (DOMElement) sib.getNextSibling())
{
if(sib.getTagName().equals(elt.getTagName())){
count++;
}
}
}catch(Exception ee){
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
你的标题谈到了getPreviousSibling()
,但你的代码只使用getNextSibling()
- 为什么?我不明白你为什么要使用getNextSibling()
...你想知道在当前的元素之前有多少同名的元素,而不是在它之后有多少元素.
您正在捕捉和吞咽异常这一事实也是非常可疑的......您为什么要这样做?如果您有异常,该方法不应该以异常终止吗?
您还应该考虑getPreviousSibling
可能不返回元素的事实- 例如,它可能返回文本节点.你想跳过那些 - 目前你会得到一个例外,它将终止循环并返回当前计数.
如果这些没有帮助,请发布一些示例XML,指出一个节点,并说明代码当前返回的内容(以及发布更新的代码).只是说,它不返回正确的计数是几乎没有说什么它有用不回来,你希望它返回.
编辑:这是我期望代码看起来像:
public static int getElementIndex(Element original) {
int count = 1;
for (Node node = original.getPreviousSibling(); node != null;
node = node.getPreviousSibling()) {
if (node instanceof Element) {
Element element = (Element) node;
if (element.getTagName().equals(original.getTagName()) {
count++;
}
}
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用if (node.getNodeType() == Node.ELEMENT_NODE)
而不是instanceof
测试.