我正在使用 javax.swing.JTree
可视化 XML 文件。使用了 this 中的代码和 this问题,我陷入了从节点添加属性作为叶子的困境。
这个简单的 XML:
<?xml version="1.0" encoding="utf-8"?>
<!-- comment -->
<MYXML xmlns="">
<Header id=""></Header>
<Product id="" name="">
<Description>Some text</Description>
<Ref id=""></Ref>
<Data id="">
<Ref id=""></Ref>
</Data>
<Form id=""></Form>
</Product>
</MYXML>
被解析为org.w3c.dom.Document
并作为org.w3c.dom.Node
传递以递归地构建JTree:
private DefaultMutableTreeNode buildTreeNode(Node rootNode) {
DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(
rootNode.getNodeName());
NodeList children = rootNode.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
short nodeType = node.getNodeType();
if (nodeType == Node.ELEMENT_NODE) {
treeNode.add(buildTreeNode(node));
// FIXME attributes should be leaves of their nodes
if (node.hasAttributes()) {
NamedNodeMap attributes = node.getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
Node attr = attributes.item(j);
treeNode.add(new DefaultMutableTreeNode("@" + attr));
}
}
} else if (nodeType == Node.TEXT_NODE) {
String text = node.getTextContent().trim();
if (!text.equals("")) {
treeNode.add(new DefaultMutableTreeNode(text));
}
} else if (nodeType == Node.COMMENT_NODE) {
String comment = node.getNodeValue().trim();
treeNode.add(new DefaultMutableTreeNode("#" + comment));
}
}
return treeNode;
}
结果不是我想要的:
叶子“Header”、“Ref”和“Form”应该是节点,所有属性(标记为@
)应该是其节点的叶子。如何通过递归方法实现这一目标?
这是我在 Gist 上的工作示例.
编辑:我想通了并在下面回答了我的问题。
最佳答案
TreeNode中有一个isLeaf方法,你需要实现它,因为,当该节点没有 child 时(childrenCount==0),它通常返回true,否则返回false。您希望将其标记为节点元素,而不管其子元素数量如何,因此您需要实现/覆盖此方法,以便它将返回您需要的内容。
您的算法也存在问题:
您需要检查您的节点是否有子节点,或者只是一个带有叶子的结束节点。您需要区分这两者,并实现正确的处理逻辑,这取决于您如何在代码中解释此 xml。
关于java - JTree:如何添加节点的属性作为自己的叶子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30405462/