简体   繁体   English

使用DOM解析器将树节点填充到XML文档之外的JTree中

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

I am a beginner in Java. 我是Java的初学者。 I am trying to populate a JTree dynamically from an XML file(helloWorld.xml in this case), using DOM parser. 我正在尝试使用DOM解析器从XML文件(在本例中为helloWorld.xml)动态填充JTree。 I took help for my code from the flowing Thread: Creating a JTree out of an XML document using DOM parser 我从流动的线程那里获得了代码帮助: 使用DOM解析器从XML文档中创建JTree

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. 当我执行println()时,我可以看到正在遍历子节点。 But the same nodes are not getting added to my JTree(It showing zero(0) height). 但是相同的节点没有被添加到我的JTree中(它显示零(0)高度)。

My source XML file is the same as in the above thread: 我的源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>

The output i get is a blank JFrame and this in the output console: run: 我得到的输出是一个空白的JFrame,并在输出控制台中运行:

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. 基本上,您想根据要构造的结构将XML的内容加载到TreeModel

Once you have the model loaded, you apply it to an instance of JTree 加载模型后,将其应用于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 详细了解如何使用树木

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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