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);
}
}
//------------------------------------------------------------------------------
}
这是我解析 XML 文档并将其表示为JTree
. 问题是我只得到根节点JTree
而没有别的。我尝试使用与此类似的代码来遍历目录结构,并且有效。我不知道为什么这没有给我我期望的结果。
图片
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>
注意:如果我输入打印元素和文本节点System.out.println()
的visit()
方法,它会打印得很好。只是没有添加节点。