我正在使用NetBeans在Java中开发一个小型桌面应用程序。在某些时候,我需要从XML文件中读取数据,并在阅读后我需要将其存储在我的自定义类的对象中。我成功完成了上述任务(即我读取XML数据并将数据存储在我的自定义类的对象中)。现在我想用该对象填充JTree。假设我的XML看起来像这样:
<Employees>
<Classification type="permanent">
<Emp>
<name>Emp1_Name<name/>
</Emp>
<Emp>
<name>Emp2_Name<name/>
</Emp> </Classification>
<Classification type="part time">
<Emp>
<name>Emp1_Name<name/>
</Emp>
<Emp>
<name>Emp2_Name<name/>
</Emp> </Classification>
</Classification>
</Employees>
现在我希望我的树看起来像这样
Employees
Permanent Employees
Emp1_Name
Emp2_Name
Part Time Employees
Emp1_Name
Emp2_Name
答案 0 :(得分:2)
这可能对您有用:
http://www.arsitech.com/xml/jdom_xml_jtree.php
http://www.wsoftware.de/SpeedJG/XMLTreeView.html
代码来自: Java: How to display an XML file in a JTree
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;
}
答案 1 :(得分:1)
您需要编写函数来获取应用程序对象的信息,您可以使用SAX或DOM解析器
DefaultMutableTreeNode root = new DefaultMutableTreeNode()
Object object = //function to fetch the information of your Object
// if you are storing all objects in a vector then read element of object
root.add((DefaultMutableTreeNode)object)