Relative XPath
Posted: Tue Jul 05, 2011 11:53 pm
If I have AuthorAccess A and AuthorElement E how do I find number of previous siblings of E?
Like this:If I have AuthorAccess A and AuthorElement E how do I find number of previous siblings of E?
Code: Select all
//The current element
AuthorElement elem = ......
AuthorNode parent = elem.getParent();
List<AuthorNode> contentNodes = ((AuthorParentNode)parent).getContentNodes();
int indexInParent = contentNodes.indexOf(elem);
for (int i = indexInParent - 1; i >= 0; i--) {
AuthorNode previousSibling = contentNodes.get(i);
}
We have such methods in our implementation but nothing exposed in the API. If you can give us an use case maybe we can add such a method in the API. Of course you can implement it yourself, here is some simplified code from the method we've got (without taking namespaces into account):And in general how do I do relative XPath given a particular AuthorElement?
Code: Select all
/**
* Get the xpath expression for the element from the caret position.
*
* counts the sibling elements before current element having the same name. The indexes are 1 based.
* @param currentNode
* @return The XPath expression
*/
public static String getXpathExpresionSimplified(AuthorNode currentNode) {
String toReturn = "";
while (currentNode != null && AuthorNode.NODE_TYPE_DOCUMENT != currentNode.getType()) {
// Traverse the ancestors of the current node and build xpath expr.
String name = currentNode.getName();
//
// Find the index of current element in the parent
//
String indexInParent = "";
AuthorParentNode parent = (AuthorParentNode) currentNode.getParent();
if (parent != null && AuthorNode.NODE_TYPE_DOCUMENT != parent.getType()) {
List children = parent.getContentNodes();
int index = 0;
for (Iterator iter = children.iterator(); iter.hasNext();) {
AuthorNode child = (AuthorNode) iter.next();
if (name.equals(child.getName())) {
index ++;
if (child == currentNode) {
indexInParent = "[" + index + "]";
break;
}
}
}
}
//
// Adds the XPath section corresponding to the current token item.
//
switch (currentNode.getType()) {
case AuthorNode.NODE_TYPE_ELEMENT:
toReturn = "/" + name + indexInParent + toReturn;
break;
case AuthorNode.NODE_TYPE_COMMENT:
// The token is comment.
toReturn = "/" + "comment()" + indexInParent + toReturn;
break;
case AuthorNode.NODE_TYPE_PI:
// The token is PI.
toReturn = "/" + "processing-instruction()" + indexInParent + toReturn;
break;
}
currentNode = currentNode.getParent();
}
return toReturn;
}
Code: Select all
AuthorNode[] findNodesByXPath(java.lang.String xpathExpression, AuthorNode staringPoint)
Code: Select all
findNodesByXPath("descendant::*", element)