title: Java: get xpath of element in org.w3c.dom document
body: <p>I've written what I want to achieve. however, <code>getElementIdx()</code> function doesn't return proper count. There's an issue with <code>getPreviousSibling()</code> but I don't know why.</p>
  
  <pre><code>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 &gt;= 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;
      }
  </code></pre>