Question

How can I get the corresponding XPath Query String from a selected TreePath?

a
|-b
  +-c
|-b
  +-d

If I select "d" I want to get something like /a/b[2]/d

EDIT: For now I wanted to loop through the tree.getSelectionPath().toString().split(",") but the information you will get is /a/b/d - you can not figure out that b should be b[2]

Was it helpful?

Solution

Finally I got it - maybe someone else is interested in a solution

    DefaultMutableTreeNode selected = (DefaultMutableTreeNode) tree.getSelectionPath().getLastPathComponent();

    String xpath = "";
    while (selected.getParent() != null) {
        int index = 1;
        String tag = selected.toString();
        DefaultMutableTreeNode selected2 = selected;
        while ((selected2 = selected2.getPreviousSibling()) != null) {
            if (tag.equals(selected2.toString())) index++;
        }

        xpath = "/" + tag + "[" + index + "]" + xpath;
        if (selected.getParent() == null) {
            selected = null;
        } else {
            selected = (DefaultMutableTreeNode) selected.getParent();
        }
    }

    LOG.info(xpath);

OTHER TIPS

If you use the getIndex(TreeNode) you don't have to loop over all the siblings over and over again. just remember that the tree uses 0-based indexing so you will have to add +1 to get the xpath index.

Also that if(selected.getParent == null) is not needed and only servers to a potentiall NullPointerException if it loops again. So you can begin shrink the code down to this for a slightly smaller snippet.

    String xpath = "";
    while (selected.getParent() != null) {                       
        TreeNode parent = selected.getParent();

        int index = parent.getIndex(selected) + 1;

        xpath = "/" + selected.toString() + "[" + index + "]" + xpath;

        selected = (DefaultMutableTreeNode) selected.getParent();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top