62,621
社区成员
发帖
与我相关
我的任务
分享
public class VSX {
public TreeModel parse(String filename) {
SAXParserFactory factory = SAXParserFactory.newInstance( );
XMLTreeHandler handler = new XMLTreeHandler( );
try {
// Parse the input.
SAXParser saxParser = factory.newSAXParser( );
saxParser.parse( new File(filename), handler);
}
catch (Exception e) {
System.err.println("File Read Error: " + e);
e.printStackTrace( );
return new DefaultTreeModel(new DefaultMutableTreeNode("error"));
}
return new DefaultTreeModel(handler.getRoot( ));
}
}
public class XMLTreeHandler extends DefaultHandler {
private DefaultMutableTreeNode root, currentNode;
public DefaultMutableTreeNode getRoot( ) {
return root;
}
// SAX parser handler methods
public void startElement(String namespaceURI, String lName, String qName,
Attributes attrs) throws SAXException {
String eName = lName; // Element name
if ("".equals(eName))
eName = qName;
Tag t = new Tag(eName, attrs);
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(t);
if (currentNode == null) {
root = newNode;
}
else {
// Must not be the root node
currentNode.add(newNode);
}
currentNode = newNode;
}
public void endElement(String namespaceURI, String sName, String qName)
throws SAXException {
currentNode = (DefaultMutableTreeNode)currentNode.getParent( );
}
public void characters(char buf[], int offset, int len) throws SAXException {
String s = new String(buf, offset, len).trim( );
((Tag)currentNode.getUserObject( )).addData(s);
}
}
saxParser.parse( new File(filename), handler);public class XMLTreeHandler extends DefaultHandler