如何从选定的TreePath中获取相应的XPath查询字符串?javax.swing.tree.TreePath对XPath查询字符串的选择
a
|-b
+-c
|-b
+-d
如果我选择 “d” 我想要得到的东西像/ A/B [2]/d
编辑: 现在我通过tree.getSelectionPath()想循环的toString ().split(“,”)但你会得到的信息是/ a/b/d - 你不知道b应该是b [2]
如何从选定的TreePath中获取相应的XPath查询字符串?javax.swing.tree.TreePath对XPath查询字符串的选择
a
|-b
+-c
|-b
+-d
如果我选择 “d” 我想要得到的东西像/ A/B [2]/d
编辑: 现在我通过tree.getSelectionPath()想循环的toString ().split(“,”)但你会得到的信息是/ a/b/d - 你不知道b应该是b [2]
最后我明白了 - 也许别人有兴趣在解决方案中
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);
如果使用getIndex(TreeNode),则不必一遍又一遍地遍历所有兄弟节点。请记住树使用基于0的索引,因此您必须添加+1才能获取xpath索引。
此外,如果(selected.getParent == null)不需要,并且只有服务器到一个潜在的NullPointerException,如果它再次循环。 因此,您可以开始将代码缩小到稍微小一些的代码片段。
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();
}
[你有什么试过](http://whathaveyoutried.com)? – 2013-02-27 13:15:05
@Eric Galluzzo:看我的编辑 – KIC 2013-02-27 13:41:08