I have translated the following Javascript code to Java. The problem occurs at sib;
http://snippets.dzone.com/posts/show/3754
I have never seen such for statements. What does it do exactly when you add a semicolon? Is this like while() statement?
public static String getElementXpath(DOMElement elt){
String path = "";
for (;elt.ELEMENT_NODE == elt.getNodeType(); elt = (DOMElement) elt.getParentNode()){
int idx = getElementIdx(elt);
}
return path;
}
private static int getElementIdx(DOMElement elt) {
int count = 1;
for (DOMElement sib = (DOMElement) elt.getPreviousSibling(); sib ; sib = (DOMElement) sib.getPreviousSibling())
{
if(sib.ELEMENT_NODE == sib.getNodeType() && sib.getTagName() == elt.getTagName()) count++;
}
return count;
}
If you meant the first
forloop:then the initial
;indicates that there is no initialisation to be done.A normal
forloop is: for (initialise; expression; update) so your one only has the expression and update parts. There is no need for initialisation in your case because theDOMElementis passed in as a parameter and doesn’t require any other steps before you use it in theforloopIn response to comment:
Before each iteration of the loop the test
elt.ELEMENT_NODE == elt.getNodeType()is performed. This tests that the node referenced byeltis an element node (i.e. not a text node, attribute node, comment node etc). If the test fails then the body of the loop is executed.In the body of the loop,
getElementIdxis called to calcuate the relative position of this node amongst any siblings of the same name. This value is stored inidxbut nothing is done with it and the value is then discarded.After the body of the loop is executed, the update
elt = (DOMElement) elt.getParentNode()is performed. This changeseltto reference the parent node of the node it previously referenced.As a first step, I would change
elt.ELEMENT_NODE == elt.getNodeType()toNode.DOCUMENT_NODE == elt.getNodeType()(see comment from Paŭlo Ebermann below) as this will cause your program to work back through the parent nodes until it finds the root of the document