📄 saxtreeviewer.java
字号:
/*
* Created on 2005-11-20
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
/*--
Copyright (C) 2001 Brett McLaughlin.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the disclaimer that follows
these conditions in the documentation and/or other materials
provided with the distribution.
3. The name "Java and XML" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact brett@newInstance.com.
In addition, we request (but do not require) that you include in the
end-user documentation provided with the redistribution and/or in the
software itself an acknowledgement equivalent to the following:
"This product includes software developed for the
'Java and XML' book, by Brett McLaughlin (O'Reilly & Associates)."
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
// This is an XML book - no need for explicit Swing imports
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class SAXTreeViewer extends JFrame {
/** Default parser to use */
private String vendorParserClass =
"org.apache.xerces.parsers.SAXParser";
/** The base tree to render */
private JTree jTree;
/** Tree model to use */
DefaultTreeModel defaultTreeModel;
/**
* <p> This initializes the needed Swing settings. </p>
*/
public SAXTreeViewer() {
// Handle Swing setup
super("SAX Tree Viewer");
setSize(600, 450);
}
/**
* <p> This will construct the tree using Swing. </p>
*
* @param filename <code>String</code> path to XML document.
*/
public void init(String xmlURI) throws IOException, SAXException {
DefaultMutableTreeNode base =
new DefaultMutableTreeNode("XML Document: " +
xmlURI);
// Build the tree model
defaultTreeModel = new DefaultTreeModel(base);
jTree = new JTree(defaultTreeModel);
// Construct the tree hierarchy
buildTree(defaultTreeModel, base, xmlURI);
// Display the results
getContentPane().add(new JScrollPane(jTree),
BorderLayout.CENTER);
}
/**
* <p>This handles building the Swing UI tree.</p>
*
* @param treeModel Swing component to build upon.
* @param base tree node to build on.
* @param xmlURI URI to build XML document from.
* @throws <code>IOException</code> - when reading the XML URI fails.
* @throws <code>SAXException</code> - when errors in parsing occur.
*/
public void buildTree(DefaultTreeModel treeModel,
DefaultMutableTreeNode base, String xmlURI)
throws IOException, SAXException {
// Create instances needed for parsing
XMLReader reader =
XMLReaderFactory.createXMLReader(vendorParserClass);
ContentHandler jTreeContentHandler =
new JTreeContentHandler(treeModel, base);
ErrorHandler jTreeErrorHandler = new JTreeErrorHandler();
// Register content handler
reader.setContentHandler(jTreeContentHandler);
// Register error handler
reader.setErrorHandler(jTreeErrorHandler);
// Parse
InputSource inputSource =
new InputSource(xmlURI);
reader.parse(inputSource);
}
/**
* <p> Static entry point for running the viewer. </p>
*/
public static void main(String[] args) {
try {
if (args.length != 1) {
System.out.println(
"Usage: java SAXTreeViewer " +
"[XML Document URI]");
System.exit(0);
}
SAXTreeViewer viewer = new SAXTreeViewer();
viewer.init(args[0]);
viewer.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* <b><code>JTreeContentHandler</code></b> implements the SAX
* <code>ContentHandler</code> interface and defines callback
* behavior for the SAX callbacks associated with an XML
* document's content, bulding up JTree nodes.
*/class JTreeContentHandler implements ContentHandler {
/** Hold onto the locator for location information */
private Locator locator;
/** Store URI to prefix mappings */
private Map namespaceMappings;
/** Tree Model to add nodes to */
private DefaultTreeModel treeModel;
/** Current node to add sub-nodes to */
private DefaultMutableTreeNode current;
/**
* <p> Set up for working with the JTree. </p>
*
* @param treeModel tree to add nodes to.
* @param base node to start adding sub-nodes to.
*/
public JTreeContentHandler(DefaultTreeModel treeModel,
DefaultMutableTreeNode base) {
this.treeModel = treeModel;
this.current = base;
this.namespaceMappings = new HashMap();
}
/**
* <p>
* Provide reference to <code>Locator</code> which provides
* information about where in a document callbacks occur.
* </p>
*
* @param locator <code>Locator</code> object tied to callback
* process
*/
public void setDocumentLocator(Locator locator) {
// Save this for later use
this.locator = locator;
}
/**
* <p>
* This indicates the start of a Document parse-this precedes
* all callbacks in all SAX Handlers with the sole exception
* of <code>{@link #setDocumentLocator}</code>.
* </p>
*
* @throws <code>SAXException</code> when things go wrong
*/
public void startDocument() throws SAXException {
// No visual events occur here
}
/**
* <p>
* This indicates the end of a Document parse-this occurs after
* all callbacks in all SAX Handlers.</code>.
* </p>
*
* @throws <code>SAXException</code> when things go wrong
*/
public void endDocument() throws SAXException {
// No visual events occur here
}
/**
* <p>
* This indicates that a processing instruction (other than
* the XML declaration) has been encountered.
* </p>
*
* @param target <code>String</code> target of PI
* @param data <code>String</code containing all data sent to the PI.
* This typically looks like one or more attribute value
* pairs.
* @throws <code>SAXException</code> when things go wrong
*/
public void processingInstruction(String target, String data)
throws SAXException {
DefaultMutableTreeNode pi =
new DefaultMutableTreeNode("PI (target = '" + target +
"', data = '" + data + "')");
current.add(pi);
}
/**
* <p>
* This indicates the beginning of an XML Namespace prefix
* mapping. Although this typically occurs within the root element
* of an XML document, it can occur at any point within the
* document. Note that a prefix mapping on an element triggers
* this callback <i>before</i> the callback for the actual element
* itself (<code>{@link #startElement}</code>) occurs.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -