FileDocCategorySizeDatePackage
SimpleXPathViewer.javaAPI DocExample9334Sat Sep 01 16:10:14 BST 2001javaxml2

SimpleXPathViewer

public class SimpleXPathViewer extends JFrame
This displays the XML document given on the command line in a JTree. When a user clicks on a node, this displays the XPath text that is related to that node according to the following specification: Element - XPath statement that will uniquely select the node Attribute - XPath statement that will select any element with that attribute and value Text - XPath statement that will return the selected text others - (currently) ignored

Fields Summary
EventHandler
eventHandler
The event handler inner class
private JTextField
statusText
A text field for displaying the XPath for the selectected node
private JTree
jdomTree
The JTree used to display the nodes of the xml document
private DefaultTreeSelectionModel
selectionModel
The selection model used to determine which node was clicked
private String
filename
The filename containing the xml file to view
private static Element
lastElement
Temporary hack to get around the lack of a text node
Constructors Summary
public SimpleXPathViewer(String fileName)

Construct an instance of the viewer.

param
fileName file to use as input

        super();
        this.filename = fileName;
        setSize(600, 450);
        initialize();
    
Methods Summary
private voidbuildTree(JDOMNode node, javax.swing.tree.DefaultMutableTreeNode treeNode)
Recursively build the JTree from nodes of the JDOM Document

param
node JDOMNode
param
treeNode javax.swing.tree.DefaultMutableTreeNode

        // If this is a whitespace node or unhandled node, ignore it
        if ((node == null) || (node.toString().trim().equals(""))) {
            return;
        }

        DefaultMutableTreeNode newTreeNode = new DefaultMutableTreeNode(node);
		
        // Walk over the children of the node 
        Iterator i = node.iterator();
        while (i.hasNext()) {
            // Create JDOMNodes on the children and add to the tree
            JDOMNode newNode = createNode(i.next());
            buildTree(newNode, newTreeNode);
        }

        // After all the children have been added, connect to the tree
        treeNode.add(newTreeNode);
    
private voidbuildXPath(JDOMNode node)
Put the xpath path to the selected node in the status bar

param
node JDOMNode

        statusText.setText(new XPathDisplayNode(node).getXPath());
    
private JDOMNodecreateNode(java.lang.Object node)

Factory method to create nodes according to the type of the given object.

param
node object to wrap.
return
JDOMNode - created node.

        if (node instanceof Element) {
            lastElement = (Element)node;
            return new ElementNode((Element)node);
        }

        if (node instanceof Attribute) {
            return new AttributeNode((Attribute)node);
        }

        if (node instanceof String) {
            return new TextNode((String)node).setParent(lastElement);
        }

        // All other nodes are not implemented
        return null;
    
private voidinitConnections()

This initializes connections between swing components, models and event handlers.

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        // Setup the JTree and a pane to display it in
        jdomTree = new JTree();
        jdomTree.setName("JDOM Tree");
        jdomTree.addTreeSelectionListener(eventHandler);
        selectionModel = (DefaultTreeSelectionModel)jdomTree.getSelectionModel();
        getContentPane().add(new JScrollPane(jdomTree), BorderLayout.CENTER);

        // Setup a text box for use in a status bar
        statusText = new JTextField("Click on an element to view xpath");
        JPanel statusBarPane= new JPanel();
        statusBarPane.setLayout(new BorderLayout());
        statusBarPane.add(statusText, BorderLayout.CENTER );
        getContentPane().add(statusBarPane, BorderLayout.SOUTH);
    
private voidinitialize()

Initialize the class, load and display the xml document.

        setTitle("Simple XPath Viewer");

        // Setup the UI
        initConnections();
		
        // Load the JDOM Document
        Document doc = loadDocument(filename);

        // Create the initial JDOMNode from the Factory method
        JDOMNode root = createNode(doc.getRootElement());
			
        // Create the root node of the JTree and build it from the JDOM Document
        DefaultMutableTreeNode treeNode = 
            new DefaultMutableTreeNode("Document: " + filename);
        buildTree(root, treeNode);

        // Add the node to the tree's model
        ((DefaultTreeModel)jdomTree.getModel()).setRoot(treeNode);
    
private DocumentloadDocument(java.lang.String filename)

Load the given xml file for display.

param
filename XML file to load.
return
Document - JDOM XML representation.

        SAXBuilder builder = new SAXBuilder();
        builder.setIgnoringElementContentWhitespace(true);
        return builder.build(new File(filename));
    
public static voidmain(java.lang.String[] args)

Static entry point

        try {
            if (args.length != 1) {
                System.out.println("Usage: java javaxml2.SimpleXPathViewer " + 
                    "[XML Document filename]");
                return;
            }

            /* Create the frame */
            SimpleXPathViewer viewer= new SimpleXPathViewer(args[0]);

            /* Add a windowListener for the windowClosedEvent */
            viewer.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosed(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    };
                });
            viewer.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }