views:

564

answers:

2

Hi,

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.

Is anyone aware of a way to get a JTree to display the contents of an XML file, parsed with SAX?

Thanks!

+5  A: 

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;         
}
Itay
+1  A: 

check following links:

http://www.jroller.com/santhosh/entry/xml_viewer_with_swing

http://www.jroller.com/santhosh/entry/xml_viewer_with_swing_part

Santhosh Kumar T
Hi @Santosh, I actually did find and use your articles before asking the question... I find @Itay's method much simpler than implementing a custom Model and Renderer, as you have in your article. Although I must say that if I had wanted to do things more complicated than just a simple `JTree`, such as the treetable, as you have, then I would definitely go for your method. Cheers!
bguiz