Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

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:

  1. 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.

  2. 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.

  3. 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.

  4. 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 23–1 shows the initial file chooser used to select the perennials.xml file (Listing 23.4; see Listing 23.5 for the DTD). Figures 23–2 and 23–3 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 23–1 JFileChooser that uses ExtensionFileFilter (Listing 23.3) to interactively select an XML file.

Figure 23–2 JTree representation of root node and top-level child elements of perennials.xml (Listing 23.4).

Figure 23–3 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">   

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020