Example: TreeViewer
import javax.swing.*;
import javax.swing.tree.*;
import nu.xom.*;
public class TreeViewer {
// Initialize the per-element data structures
public static MutableTreeNode processElement(Element element) {
String data;
if (element.getNamespaceURI().equals(""))
data = element.getLocalName();
else {
data =
'{'
+ element.getNamespaceURI()
+ "} "
+ element.getQualifiedName();
}
MutableTreeNode node = new DefaultMutableTreeNode(data);
Elements children = element.getChildElements();
for (int i = 0; i < children.size(); i++) {
node.insert(processElement(children.get(i)), i);
}
return node;
}
public static void display(Document doc) {
Element root = doc.getRootElement();
JTree tree = new JTree(processElement(root));
JScrollPane treeView = new JScrollPane(tree);
JFrame f = new JFrame("XML Tree");
String version = System.getProperty("java.version");
if (version.startsWith("1.2") || version.startsWith("1.1")) {
f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
else {
// JFrame.EXIT_ON_CLOSE == 3 but this named constant is not
// available in Java 1.2
f.setDefaultCloseOperation(3);
}
f.getContentPane().add(treeView);
f.pack();
f.show();
}
public static void main(String[] args) {
try {
Builder builder = new Builder();
for (int i = 0; i < args.length; i++) {
Document doc = builder.build(args[i]);
display(doc);
}
}
catch (Exception ex) {
System.err.println(ex);
}
} // end main()
} // end TreeViewer