Java: how to display XML file in JTree

I would like to have a way to display the contents of an XML file in JTree . I already accomplished this with the DOM by executing a custom TreeModel (and TreeCellRenderer ). However, he is very clumsy (a lot of workaround and hacker) and quite rude around the edges.

Does anyone know how to get JTree to display the contents of an XML file parsed using SAX?

Thanks!

+4
source share
1 answer

Here is the code I'm using. It is based on the Dom4J API, but you can easily convert it to the API 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; } 
+13
source

All Articles