欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

JDOM: 解析XML并在树形控件(JTree)中显示,jdomjtree,SimpleXPathV

来源: javaer 分享于  点击 33715 次 点评:163

JDOM: 解析XML并在树形控件(JTree)中显示,jdomjtree,SimpleXPathV


SimpleXPathViewer.java

package javaxml2;import java.awt.*;import java.io.File;import javax.swing.*;import javax.swing.tree.*;import javax.swing.event.*;import java.util.Iterator;// JDOM importsimport org.jdom.*;import org.jdom.input.SAXBuilder;/** * 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 */public class SimpleXPathViewer extends JFrame {    /** The event handler inner class */    EventHandler eventHandler = new EventHandler();    /** A text field for displaying the XPath for the selectected node */    private JTextField statusText;    /** The JTree used to display the nodes of the xml document */    private JTree jdomTree;    /** The selection model used to determine which node was clicked */    private DefaultTreeSelectionModel selectionModel;    /** The filename containing the xml file to view */    private String filename;    /** Temporary hack to get around the lack of a text node */    private static Element lastElement;    /**     * Simple inner class to handle various ui events and delegate them     * to the appropriate methods     */    class EventHandler implements TreeSelectionListener {        public void valueChanged(TreeSelectionEvent e) {            TreePath path= selectionModel.getLeadSelectionPath();            // If you are just collapsing the tree, you may not have a new path            if (path != null) {                JDOMNode selection=                    (JDOMNode) ((DefaultMutableTreeNode)path.getLastPathComponent())                        .getUserObject();                buildXPath(selection);            }        };    };    /**     * <p>Construct an instance of the viewer.</p>     *     * @param fileName file to use as input     */    public SimpleXPathViewer(String fileName) throws Exception {        super();        this.filename = fileName;        setSize(600, 450);        initialize();    }    /**     * <p>Initialize the class, load and display the xml document.</p>     */    private void initialize() throws Exception {        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);    }    /**     * <p>This initializes connections between swing components, models     *   and event handlers.</p>     */    private void initConnections() {        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);    }    /**     * <p>Load the given xml file for display.</p>     *     * @param filename XML file to load.     * @return <code>Document</code> - JDOM XML representation.     */    private Document loadDocument(String filename) throws JDOMException {        SAXBuilder builder = new SAXBuilder();        builder.setIgnoringElementContentWhitespace(true);        return builder.build(new File(filename));    }    /**     * <p>Factory method to create nodes according to the type of     *   the given object.</p>     *     * @param node object to wrap.     * @return <code>JDOMNode</code> - created node.     */    private JDOMNode createNode(Object 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;    }    /**     * Recursively build the JTree from nodes of the JDOM Document     *     * @param node JDOMNode     * @param treeNode javax.swing.tree.DefaultMutableTreeNode     */    private void buildTree(JDOMNode node, DefaultMutableTreeNode treeNode) {        // 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);    }    /**     * Put the xpath path to the selected node in the status bar     *     * @param node JDOMNode     */    private void buildXPath(JDOMNode node) {        statusText.setText(new XPathDisplayNode(node).getXPath());    }    /**     * <p>Static entry point</p>     */    public static void main(java.lang.String[] args) {        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();        }    }}
相关栏目:

用户点评