Java:在org.w3c.dom文档中获取元素的xpath

KJW*_*KJW 7 java dom

我已经写了我想要实现的目标.但是,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)

Jon*_*eet 6

你的标题谈到了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测试.