Java:如何在JTree中显示XML文件 [英] Java: How to display an XML file in a JTree
问题描述
我希望能够在 JTree
中显示XML文件的内容。我已经使用DOM,通过实现自定义 TreeModel
(以及 TreeCellRenderer
)来完成此操作。然而它非常笨重(很多变通方法和hackery)并且相当粗糙。
I would like to have a way to display the contents of an XML file in a JTree
. I have already accomplished this using DOM, by implementing a custom TreeModel
(and TreeCellRenderer
). However it is very clunky (much workaround-ery and hackery) and rather rough around the edges.
是否有人知道如何获得 JTree
显示XML文件的内容,用SAX解析?
Is anyone aware of a way to get a JTree
to display the contents of an XML file, parsed with SAX?
谢谢!
推荐答案
这是我使用的代码。它基于Dom4J的API,但您可以轻松地将其转换为您喜欢的XML库的API:
Here's the code that I use. It is based on the API of Dom4J, but you can easily convert it to the APIs of your favorite XML library:
public JTree build(String pathToXml) throws Exception {
SAXReader reader = new SAXReader();
Document doc = reader.read(pathToXml);
return new JTree(build(doc.getRootElement()));
}
public DefaultMutableTreeNode build(Element e) {
DefaultMutableTreeNode result = new DefaultMutableTreeNode(e.getText());
for(Object o : e.elements()) {
Element child = (Element) o;
result.add(build(child));
}
return result;
}
这篇关于Java:如何在JTree中显示XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!