Search code examples
javaxmlswingdomjtree

Creating a JTree out of an XML document using DOM parser


package xml;

import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

import java.io.*;

public class ThirdParser extends JFrame{
    DocumentBuilderFactory factory;
    DocumentBuilder builder;
    File f;
    Document d;
    JTree tree;
    JScrollPane scroll;
//------------------------------------------------------------------------------
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            @Override public void run(){
                new ThirdParser();
            }
        });
    }
//------------------------------------------------------------------------------
    public ThirdParser(){
        try{

            factory = DocumentBuilderFactory.newInstance();
            builder = factory.newDocumentBuilder();
            f = new File("E:/Website Projects/XML/helloWorld.xml");
            d = builder.parse(f);
            String people = "people";
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(people);
            tree = new JTree(node);
            Element e = d.getDocumentElement();

            if(e.hasChildNodes()){
                DefaultMutableTreeNode root = new DefaultMutableTreeNode
                                                            (e.getTagName());
                NodeList children = e.getChildNodes();
                for(int i=0;i<children.getLength();i++){
                    Node child = children.item(i);
                    visit(child,root);
                }
            }
        }catch(ParserConfigurationException e){
            e.printStackTrace();
        }catch(SAXException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
//      scroll = new JScrollPane(tree);

        this.add(tree);
        this.setVisible(true);
        this.pack();
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    }
//------------------------------------------------------------------------------
    public void visit(Node child,DefaultMutableTreeNode parent){
        short type = child.getNodeType();
        if(type == Node.ELEMENT_NODE){
            Element e = (Element)child;
            DefaultMutableTreeNode node = new DefaultMutableTreeNode
                                        (e.getTagName());
            parent.add(node);

            if(e.hasChildNodes()){
                NodeList list = e.getChildNodes();
                for(int i=0;i<list.getLength();i++){
                    visit(list.item(i),node);
                }
            }

        }else if(type == Node.TEXT_NODE){
            Text t = (Text)child;
            String textContent = t.getTextContent();
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(
                    textContent);
            parent.add(node);
        }
    }
//------------------------------------------------------------------------------
}  

This is my code to parse an XML document and represent it as a JTree. The problem is that I only get the root node in the JTree and nothing else. I tried walking the directory structure with a code similar to this and that worked. I do not know why this does not give me the result I expect.

Image

enter image description here

XML

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE people SYSTEM "validator.dtd">

<people>
    <student>
        <name>John</name>
        <course>Computer Technology</course>
        <semester>6</semester>
        <scheme>E</scheme>
    </student>

    <student>
        <name>Foo</name>
        <course>Industrial Electronics</course>
        <semester>6</semester>
        <scheme>E</scheme>
    </student>
</people>

Note: If I enter System.out.println() in the visit() method to print element and text nodes, it prints fine. Just that nodes are not added.


Solution

  • Looks like you are adding the children to the wrong parent node. The tree root is set tree = new JTree(node);, but then you add children to DefaultMutableTreeNode root = new DefaultMutableTreeNode(e.getTagName()); which is not part of the tree at all. Quick fix would be changing:

    visit(child,root);
    

    to

    visit(child,node);
    

    Or execute node.add(root); once all nodes were visited.