- Parsing XML Documents with DOM Level 2
- DOM Example: Representing an XML Document as a JTree
- Parsing XML Documents with SAX 2.0
- SAX Example 1: Printing the Outline of an XML Document
- SAX Example 2: Counting Book Orders
- Transforming XML with XSLT
- XSLT Example 1: XSLT Document Editor
- XSLT Example 2: Custom JSP Tag
- Summary
23.2 DOM Example: Representing an XML Document as a JTree
Listing 23.1 shows a class that represents the basic structure of an XML document as a JTree. Each element is represented as a node in the tree, with tree node being either the element name or the element name followed by a list of the attributes in parentheses. This class performs the following steps:
Parses and normalizes an XML document, then obtains the root element. These steps are performed exactly as described in steps one through five of the previous section.
Makes the root element into a JTree node. If the XML element has attributes (as given by node.getAttributes), the tree node is represented by a string composed of the element name (getNodeName) followed by the attributes and values in parentheses. If there are no attributes (getLength applied to the result of node.getAttributes returns 0), then just the element name is used for the tree node label.
Looks up the child elements of the current element using getChildNodes, turns them into JTree nodes, and links those JTree nodes to the parent tree node.
Recursively applies step 3 to each of the child elements.
Listing 23.2 shows a class that creates the JTree just described and places it into a JFrame. Both the parser and the XML document can be specified by the user. The parser is specified when the user invokes the program with
java -Djavax.xml.parsers.DocumentBuilderFactory=xxx XMLFrame
If no parser is specified, the Apache Xerces parser is used. The XML document can be supplied on the command line, but if it is not given, a JFileChooser is used to interactively select the file of interest. The file extensions shown by the JFi_leChooser are limited to xml and tld (JSP tag library descriptors) through use of the ExtensionFileFilter class of Listing 23.3.
Figure 231 shows the initial file chooser used to select the perennials.xml file (Listing 23.4; see Listing 23.5 for the DTD). Figures 232 and 233 show the result in its unexpanded and partially expanded forms, respectively.
Note that because the XML file specifies a DTD, Xerces-J will attempt to parse the DTD even though no validation of the document is performed. If perenni_als.dtd is not available on-line, then you can place the DTD in a dtds subdirectory (below the directory containing XMLTree) and change the DOCTYPE in perennials.xml to
<!DOCTYPE perennials SYSTEM "dtds/perennials.dtd">
Figure 231 JFileChooser that uses ExtensionFileFilter (Listing 23.3) to interactively select an XML file.
Figure 232 JTree representation of root node and top-level child elements of perennials.xml (Listing 23.4).
Figure 233 JTree representation of perennials.xml with several nodes expanded.
Listing 23.1 XMLTree.java
import java.awt.*; import javax.swing.*; import javax.swing.tree.*; import java.io.*; import org.w3c.dom.*; import javax.xml.parsers.*; /** Given a filename or a name and an input stream, * this class generates a JTree representing the * XML structure contained in the file or stream. * Parses with DOM then copies the tree structure * (minus text and comment nodes). */ public class XMLTree extends JTree { public XMLTree(String filename) throws IOException { this(filename, new FileInputStream(new File(filename))); } public XMLTree(String filename, InputStream in) { super(makeRootNode(in)); } // This method needs to be static so that it can be called // from the call to the parent constructor (super), which // occurs before the object is really built. private static DefaultMutableTreeNode makeRootNode(InputStream in) { try { // Use JAXP's DocumentBuilderFactory so that there // is no code here that is dependent on a particular // DOM parser. Use the system property // javax.xml.parsers.DocumentBuilderFactory (set either // from Java code or by using the -D option to "java"). // or jre_dir/lib/jaxp.properties to specify this. DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); // Standard DOM code from hereon. The "parse" // method invokes the parser and returns a fully parsed // Document object. We'll then recursively descend the // tree and copy non-text nodes into JTree nodes. Document document = builder.parse(in); document.getDocumentElement().normalize(); Element rootElement = document.getDocumentElement(); DefaultMutableTreeNode rootTreeNode = buildTree(rootElement); return(rootTreeNode); } catch(Exception e) { String errorMessage = "Error making root node: " + e; System.err.println(errorMessage); e.printStackTrace(); return(new DefaultMutableTreeNode(errorMessage)); } } private static DefaultMutableTreeNode buildTree(Element rootElement) { // Make a JTree node for the root, then make JTree // nodes for each child and add them to the root node. // The addChildren method is recursive. DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode(treeNodeLabel(rootElement)); addChildren(rootTreeNode, rootElement); return(rootTreeNode); } private static void addChildren (DefaultMutableTreeNode parentTreeNode, Node parentXMLElement) { // Recursive method that finds all the child elements // and adds them to the parent node. We have two types // of nodes here: the ones corresponding to the actual // XML structure and the entries of the graphical JTree. // The convention is that nodes corresponding to the // graphical JTree will have the word "tree" in the // variable name. Thus, "childElement" is the child XML // element whereas "childTreeNode" is the JTree element. // This method just copies the non-text and non-comment // nodes from the XML structure to the JTree structure. NodeList childElements = parentXMLElement.getChildNodes(); for(int i=0; i<childElements.getLength(); i++) { Node childElement = childElements.item(i); if (!(childElement instanceof Text || childElement instanceof Comment)) { DefaultMutableTreeNode childTreeNode = new DefaultMutableTreeNode (treeNodeLabel(childElement)); parentTreeNode.add(childTreeNode); addChildren(childTreeNode, childElement); } } } // If the XML element has no attributes, the JTree node // will just have the name of the XML element. If the // XML element has attributes, the names and values of the // attributes will be listed in parens after the XML // element name. For example: // XML Element: <blah> // JTree Node: blah // XML Element: <blah foo="bar" baz="quux"> // JTree Node: blah (foo=bar, baz=quux) private static String treeNodeLabel(Node childElement) { NamedNodeMap elementAttributes = childElement.getAttributes(); String treeNodeLabel = childElement.getNodeName(); if (elementAttributes != null && elementAttributes.getLength() > 0) { treeNodeLabel = treeNodeLabel + " ("; int numAttributes = elementAttributes.getLength(); for(int i=0; i<numAttributes; i++) { Node attribute = elementAttributes.item(i); if (i > 0) { treeNodeLabel = treeNodeLabel + ", "; } treeNodeLabel = treeNodeLabel + attribute.getNodeName() + "=" + attribute.getNodeValue(); } treeNodeLabel = treeNodeLabel + ")"; } return(treeNodeLabel); } }
Listing 23.2 XMLFrame.java
import java.awt.*; import javax.swing.*; import java.io.*; /** Invokes an XML parser on an XML document and displays * the document in a JTree. Both the parser and the * document can be specified by the user. The parser * is specified by invoking the program with * java -Djavax.xml.parsers.DocumentBuilderFactory=xxx XMLFrame * If no parser is specified, the Apache Xerces parser is used. * The XML document can be supplied on the command * line, but if it is not given, a JFileChooser is used * to interactively select the file of interest. */ public class XMLFrame extends JFrame { public static void main(String[] args) { String jaxpPropertyName = "javax.xml.parsers.DocumentBuilderFactory"; // Pass the parser factory in on the command line with // -D to override the use of the Apache parser. if (System.getProperty(jaxpPropertyName) == null) { String apacheXercesPropertyValue = "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"; System.setProperty(jaxpPropertyName, apacheXercesPropertyValue); } String filename; if (args.length > 0) { filename = args[0]; } else { String[] extensions = { "xml", "tld" }; WindowUtilities.setNativeLookAndFeel(); filename = ExtensionFileFilter.getFileName(".", "XML Files", extensions); if (filename == null) { filename = "test.xml"; } } new XMLFrame(filename); } public XMLFrame(String filename) { try { WindowUtilities.setNativeLookAndFeel(); JTree tree = new XMLTree(filename); JFrame frame = new JFrame(filename); frame.addWindowListener(new ExitListener()); Container content = frame.getContentPane(); content.add(new JScrollPane(tree)); frame.pack(); frame.setVisible(true); } catch(IOException ioe) { System.out.println("Error creating tree: " + ioe); } } }
Listing 23.3 ExtensionFileFilter.java
import java.io.File; import java.util.*; import javax.swing.*; import javax.swing.filechooser.FileFilter; /** A FileFilter that lets you specify which file extensions * will be displayed. Also includes a static getFileName * method that users can call to pop up a JFileChooser for * a set of file extensions. * <P> * Adapted from Sun SwingSet demo. */ public class ExtensionFileFilter extends FileFilter { public static final int LOAD = 0; public static final int SAVE = 1; private String description; private boolean allowDirectories; private Hashtable extensionsTable = new Hashtable(); private boolean allowAll = false; public ExtensionFileFilter(boolean allowDirectories) { this.allowDirectories = allowDirectories; } public ExtensionFileFilter() { this(true); } public static String getFileName(String initialDirectory, String description, String extension) { String[] extensions = new String[]{ extension }; return(getFileName(initialDirectory, description, extensions, LOAD)); } public static String getFileName(String initialDirectory, String description, String extension, int mode) { String[] extensions = new String[]{ extension }; return(getFileName(initialDirectory, description, extensions, mode)); } public static String getFileName(String initialDirectory, String description, String[] extensions) { return(getFileName(initialDirectory, description, extensions, LOAD)); } /** Pops up a JFileChooser that lists files with the * specified extensions. If the mode is SAVE, then the * dialog will have a Save button; otherwise, the dialog * will have an Open button. Returns a String corresponding * to the file's pathname, or null if Cancel was selected. */ public static String getFileName(String initialDirectory, String description, String[] extensions, int mode) { ExtensionFileFilter filter = new ExtensionFileFilter(); filter.setDescription(description); for(int i=0; i<extensions.length; i++) { String extension = extensions[i]; filter.addExtension(extension, true); } JFileChooser chooser = new JFileChooser(initialDirectory); chooser.setFileFilter(filter); int selectVal = (mode==SAVE) ? chooser.showSaveDialog(null) : chooser.showOpenDialog(null); if (selectVal == JFileChooser.APPROVE_OPTION) { String path = chooser.getSelectedFile().getAbsolutePath(); return(path); } else { JOptionPane.showMessageDialog(null, "No file selected."); return(null); } } public void addExtension(String extension, boolean caseInsensitive) { if (caseInsensitive) { extension = extension.toLowerCase(); } if (!extensionsTable.containsKey(extension)) { extensionsTable.put(extension, new Boolean(caseInsensitive)); if (extension.equals("*") || extension.equals("*.*") || extension.equals(".*")) { allowAll = true; } } } public boolean accept(File file) { if (file.isDirectory()) { return(allowDirectories); } if (allowAll) { return(true); } String name = file.getName(); int dotIndex = name.lastIndexOf('.'); if ((dotIndex == -1) || (dotIndex == name.length() - 1)) { return(false); } String extension = name.substring(dotIndex + 1); if (extensionsTable.containsKey(extension)) { return(true); } Enumeration keys = extensionsTable.keys(); while(keys.hasMoreElements()) { String possibleExtension = (String)keys.nextElement(); Boolean caseFlag = (Boolean)extensionsTable.get(possibleExtension); if ((caseFlag != null) && (caseFlag.equals(Boolean.FALSE)) && (possibleExtension.equalsIgnoreCase(extension))) { return(true); } } return(false); } public void setDescription(String description) { this.description = description; } public String getDescription() { return(description); } }
Listing 23.4 perennials.xml
<?xml version="1.0" ?> <!DOCTYPE perennials SYSTEM "http://archive.corewebprogramming.com/dtds/perennials.dtd"> <perennials> <daylily status="in-stock"> <cultivar>Luxury Lace</cultivar> <award> <name>Stout Medal</name> <year>1965</year> </award> <award> <name note="small-flowered">Annie T. Giles</name> <year>1965</year> </award> <award> <name>Lenington All-American</name> <year>1970</year> </award> <bloom code="M">Midseason</bloom> <cost discount="3" currency="US">11.75</cost> </daylily> <daylily status="in-stock"> <cultivar>Green Flutter</cultivar> <award> <name>Stout Medal</name> <year>1976</year> </award> <award> <name note="small-flowered">Annie T. Giles</name> <year>1970</year> </award> <bloom code="M">Midseason</bloom> <cost discount="3+" currency="US">7.50</cost> </daylily> <daylily status="sold-out"> <cultivar>My Belle</cultivar> <award> <name>Stout Medal</name> <year>1984</year> </award> <bloom code="E">Early</bloom> <cost currency="US">12.00</cost> </daylily> <daylily status="in-stock"> <cultivar>Stella De Oro</cultivar> <award> <name>Stout Medal</name> <year>1985</year> </award> <award> <name note="miniature">Donn Fishcer Memorial Cup</name> <year>1979</year> </award> <bloom code="E-L">Early to Late</bloom> <cost discount="10+" currency="US">5.00</cost> </daylily> <daylily status="limited"> <cultivar>Brocaded Gown</cultivar> <award> <name>Stout Medal</name> <year>1989</year> </award> <bloom code="E">Early</bloom> <cost currency="US" discount="3+">14.50</cost> </daylily> </perennials>
Listing 23.5 perennials.dtd
<?xml version="1.0" encoding="ISO-8859-1" ?> <!ELEMENT perennials (daylily)*> <!ELEMENT daylily (cultivar, award*, bloom, cost)+> <!ATTLIST daylily status (in-stock | limited | sold-out) #REQUIRED> <!ELEMENT cultivar (#PCDATA)> <!ELEMENT award (name, year)> <!ELEMENT name (#PCDATA)> <!ATTLIST name note CDATA #IMPLIED> <!ELEMENT year (#PCDATA)> <!ELEMENT bloom (#PCDATA)> <!ATTLIST bloom code (E | EM | M | ML | L | E-L) #REQUIRED> <!ELEMENT cost (#PCDATA)> <!ATTLIST cost discount CDATA #IMPLIED> <!ATTLIST cost currency (US | UK | CAN) "US">