简体   繁体   English

XPath查询字符串的javax.swing.tree.TreePath选择

[英]javax.swing.tree.TreePath Selection to XPath Query String

How can I get the corresponding XPath Query String from a selected TreePath? 如何从选定的TreePath获取相应的XPath查询字符串?

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

If I select "d" I want to get something like /a/b[2]/d 如果选择“ d”,我想得到类似/ 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] 编辑:现在我想遍历tree.getSelectionPath()。toString()。split(“,”),但是您将获得的信息是/ a / b / d-您无法弄清楚b应该是b [2]

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

If you use the getIndex(TreeNode) you don't have to loop over all the siblings over and over again. 如果使用getIndex(TreeNode),则不必一遍又一遍地遍历所有同级对象。 just remember that the tree uses 0-based indexing so you will have to add +1 to get the xpath index. 只需记住,树使用基于0的索引,因此您必须添加+1才能获得xpath索引。

Also that if(selected.getParent == null) is not needed and only servers to a potentiall NullPointerException if it loops again. 另外,不需要if(selected.getParent == null),并且如果再次循环,则仅服务器可能的NullPointerException。 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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM