Java: at org w3c. Get the XPath of the element in the DOM document

I wrote down what I wanted to achieve However, the getelementidx () function does not return the correct count There is a problem with getprevioussibling(), but I don't know why

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;
    }

Solution

Your title talks about getprevioussibling (), but your code only uses getnextsibling () – why? I don't understand why you want to use getnextsibling ()... You want to know how many elements with the same name are before the current one, not after it

The fact that you catch and swallow abnormally is also very suspicious... Why do you do this? If you have an exception, shouldn't the method terminate with an exception?

You should also consider the fact that getprevioussibling may not return elements - for example, it may return a text node You want to skip those - now you get an exception that will terminate the loop and return the current count

If this doesn't help, publish some sample XML, indicate a node, and describe what the code currently returns (and publish the updated code) Just saying it doesn't return the correct count is not as useful as saying what it returns and what you expect it to return

Editor: This is what I expect the code to look like:

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;
}

You can also use if (node. Getnodetype() = = node ELEMENT_ Node) instead of instanceof test

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>