简体   繁体   中英

Populating tree nodes into a JTree out of an XML document using DOM parser

I am a beginner in Java. I am trying to populate a JTree dynamically from an XML file(helloWorld.xml in this case), using DOM parser. I took help for my code from the flowing Thread: Creating a JTree out of an XML document using DOM parser

package java_img_parser.jtrees;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLTree extends JTree {
DefaultTreeModel dm;
JTree tree = new JTree(dm);

public XMLTree() throws SAXException, IOException {
    this.dm = treeBuilder();
}

public DefaultTreeModel treeBuilder() throws SAXException, IOException{
    Node root = null;
    DefaultTreeModel dtModel = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse("helloWorld.xml");
        root = (Node)doc.getDocumentElement();
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XMLTree.class.getName()).log(Level.SEVERE, null, ex);
    }

    if(root != null){
        dtModel = new DefaultTreeModel(makeTree(root));
        dtModel.reload();
    }
    return dtModel;
}
private DefaultMutableTreeNode makeTree(Node root){
    DefaultMutableTreeNode rootTreeNode;
    rootTreeNode = new DefaultMutableTreeNode(root.getNodeName());
    NodeList nodeList = root.getChildNodes();
    for(int count=0;count<nodeList.getLength();count++){
        Node tempNode = nodeList.item(count);
        if(tempNode.getNodeType() == Node.ELEMENT_NODE){
            if(tempNode.hasChildNodes()){
                rootTreeNode.add(makeTree(tempNode));
            }
        }
    }
    System.out.println("Child-Node of"+root.getParentNode()+"is"+root.getChildNodes());
    return rootTreeNode;

}


public static void main(String args[]) throws SAXException, IOException{
    JFrame myFrame = new JFrame();
    myFrame.setTitle("XmlJTreeExample");
    myFrame.setSize(300, 500);
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myFrame.setLocationRelativeTo(null);

    XMLTree myTree = new XMLTree();
    System.out.println("Height of this JTree is:" + myTree.tree.getHeight());

    myFrame.add(myTree.tree);
    myFrame.setVisible(true);

    }
}

When i do a println() i can see that the child nodes are being traversed. But the same nodes are not getting added to my JTree(It showing zero(0) height).

My source XML file is the same as in the above thread:

<?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>

The output i get is a blank JFrame and this in the output console: run:

Child-Node of[student: null]is[name: null]
Child-Node of[student: null]is[course: null]
Child-Node of[student: null]is[semester: null]
Child-Node of[student: null]is[scheme: null]
Child-Node of[people: null]is[student: null]
Child-Node of[student: null]is[name: null]
Child-Node of[student: null]is[course: null]
Child-Node of[student: null]is[semester: null]
Child-Node of[student: null]is[scheme: null]
Child-Node of[people: null]is[student: null]
Child-Node of[#document: null]is[people: null]
Height of this JTree is:0
BUILD SUCCESSFUL (total time: 23 seconds)

Swing revolves around the model, the model is king. Basically, you want to load the contents of the XML into the TreeModel based on the structure you're trying to make.

Once you have the model loaded, you apply it to an instance of JTree

在此处输入图片说明

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class TestTree {

    public static void main(String[] args) {
        new TestTree();
    }

    public TestTree() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                DefaultMutableTreeNode root = new DefaultMutableTreeNode("People");
                DefaultTreeModel model = new DefaultTreeModel(root);
                loadXMLDocument(root);

                JTree tree = new JTree(model);
                tree.setRootVisible(false);
                tree.setShowsRootHandles(true);
                tree.expandPath(new TreePath(root));

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new JScrollPane(tree));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    protected Node getNodeFrom(Node node, String query) throws XPathExpressionException {

        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression xExpress = xPath.compile(query);
        return (Node)xExpress.evaluate(node, XPathConstants.NODE);

    }

    protected NodeList getNodesFrom(Node node, String query) throws XPathExpressionException {

        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression xExpress = xPath.compile(query);
        return (NodeList)xExpress.evaluate(node, XPathConstants.NODESET);

    }

    protected void loadXMLDocument(DefaultMutableTreeNode parent) {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(getClass().getResourceAsStream("/People.xml"));
            Node root = (Node) doc.getDocumentElement();

            NodeList students = getNodesFrom(root, "/people/student");
            for (int index = 0; index < students.getLength(); index++) {

                Node studentNode = students.item(index);
                DefaultMutableTreeNode studentTreeNode = new DefaultMutableTreeNode("Student");
                Node name = getNodeFrom(studentNode, "name");
                Node course = getNodeFrom(studentNode, "course");
                Node semester = getNodeFrom(studentNode, "semester");
                Node scheme = getNodeFrom(studentNode, "scheme");

                studentTreeNode.setUserObject(name.getTextContent());
                studentTreeNode.add(new DefaultMutableTreeNode("Course: " + course.getTextContent()));
                studentTreeNode.add(new DefaultMutableTreeNode("Semester: " + semester.getTextContent()));
                studentTreeNode.add(new DefaultMutableTreeNode("Scheme: " + scheme.getTextContent()));

                parent.add(studentTreeNode);

            }

        } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) {
            ex.printStackTrace();
        }

    }

    public class TestPane extends JPanel {

        public TestPane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.dispose();
        }

    }

}

Take a closer look at How to Use Trees for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM