In this tutorial, we will create an XML document, the contents of which can be accessed using a JFC/Swing application and from a web browser (via a Servlet). The XML document is a very simplistic representation of an address book which stores the name, email and company name of people. The XML document is written manually, and its structure is known by the Swing application and the Servlet.
This tutorial shows how Java can be used to display information in XML documents using a graphical Swing interface and an HTML based interface.
This tutorial demonstrates the simple power of XML, the information is the most important element of the equation. Information rendering engines (user interfaces) can be swapped out as is appropriate for the display device. All these rendering engines all work on the same XML document. Also, XML Parsers from different vendors can be used without making any major changes to the source code, which is another feature of using a standards based information storage format.
The applications created in this tutorial are very simple, too simple for any use in the real world. Part 2 and Part 3 of the tutorial will introduce more real world examples. developerlife hosts tutorials on lots of XML technologies – SAX, DOM, Using Java to manipulate XML, database access using XML, parsing XML from web services, etc. You can find them all here. We have tutorials on Swing and graphics programming, multithreading in Java, as well as SOA related topics, JavaME/J2ME, and GWT content as well.
While you are reading the tutorial and trying out the examples, please use the links in the references section to understand terms that you are unfamiliar with. I am assuming that you are familiar with XML (and all its related terminology) before you start this tutorial.
XML is described very well in the following tutorial – "What is XML? An introduction". XML uses markup tags as well, but, unlike HTML, XML tags describe the content, rather than the presentation of that content. By avoiding formatting tags in the data, but marking the meaning of the data itself with custom user definable tags, we actually make it easier to search various documents for a tag and view documents tailored to the preferences of the user. Using XML tags to define what your data means using the natural vocabulary of your data's domain is the key motivation for XML's invention and the basis of its usefulness. XML data can be rendered differently, depending on the destination device. The XML processor can exist on the server, the client, or both.
This tutorial explains what Document Object Model (DOM) is – "Introduction to DOM 1.0 API". DOM is a set of platform and language neutral interfaces that allow programs to access and modify the content and structure of XML documents. This specification defines a minimal set of interfaces for accessing and manipulating XML document objects. The Document Object Model is language neutral and platform independent. A DOM object is used to extract information from an XML document in a Java program (using a Java XML Parser). You can learn more about DOM in the Java and XML book.
You first need a well formed XML document and a validating XML parser in order to read information into your programs. JDOM is a good parser to use Java – you can download it here. You can use SAX to retrieve information from XML documents as well, but SAX is not used in this tutorial.
Java interfaces for DOM have been defined by the W3C and these are available in the org.w3c.dom package. The code that is required to instantiate a DOM object is different depending on which parser you use. Details on instantiating DOM objects using JDOM are provided here. You can learn more about JDOM in the Java and XML book.
DOM creates a tree based (or hierarchical) object model from the XML document. The Document (created from an XML file) contains a tree of Nodes. Methods in the Node interface allow you to find out whether a Node has children or not, and also what the type of the Node is and what its value is (if any). There are many types of Nodes, but we are interested in the following types: TEXT_NODE (=3), ELEMENT_NODE(=1). These types are static int values which are defined in the org.w3c.dom.Node.java interface created by the W3C. So a Document object is a simple container of Nodes. But, in our DTD, we have Elements, not Nodes. It just so happens that there is an interface called Element (which extends Node). It also turns out that a Node which is of type ELEMENT_NODE is also an Element. Nodes of type ELEMENT_NODE (or Elements) can also have children. How do you access these children? Through the NodeList interface of course; the NodeList interface defines 2 methods to allow the iteration of a list of Nodes. These NodeList objects are generated by Node objects of type ELEMENT_NODE (or Element objects). The Document interface has a method called getElementsByTagName(String tagname ) which returns a NodeList of all the Elements with that tag name.
Now, this procedure must be repeated on firstPersonElement for the LASTNAME, COMPANY and EMAIL elements. You might consider putting this parsing of the NodeList to get a text value in a utility method (in an XML utility class that you can write).
This was the hard part, integrating this information with a TableModel and making it available to a Servlet is relatively easy!
In order to render information in an XML document to a Swing JComponent, it is necessary to build a custom model which accesses the underlying information in a Document. It is important to remember that in Swing, the models are interfaces which allow access to the underlying data, they dont have to contain the data themselves. This is why all the models are Java interfaces, like TableModel, TreeModel and ListModel.
In this tutorial, we will create a custom TreeModel around the AddressBook.xml and then display the data in a JTable. This information will not be editable right now (that's in the next part of the tutorial). You can learn more about Swing tables in the Java Swing book.
that by the name of colNames[ c ]. This is the main "trick"
The two interesting methods in this TableModel are shown above. Note that a static String array is used to hold all the column names for this TableModel, which just happen to be the names of the Elements in a PERSON Element. This is by design, since the structure of the AddressBook.xml document is basically a 2 dimensional array, with rows and columns. The column names are known already since we made the DTD. This is why all the column names are stored in a static array called colNames. In order to access each cell in the TableModel a row and column identifier is needed. But, information in the Document is not stored by rows and columns, so we have to write a simple translation code. Every row in the TableModel is actually a PERSON Element in the Document. Now, every PERSON element has a FIRSTNAME, LASTNAME, COMPANY and EMAIL information, which is represented by the column identifier for the given row (or PERSON). In the getValue( int r, int c ) method above, this trick is used to information from the Document. Notice that before accessing Elements inside a PERSON, the column integer is converted to a column name (by using the colNames). The XmlUtils.java class is very simple and is written to work only for this example, you can write a generic one for different types of data, 1D array, 2D array, etc.
The getElement() method is very straighforward, it is used to get the PERSON Element in the row index of the TableModel. Once you have a PERSON Element, you need to extract information from its column indexes. This is where the getValue() method comes in. Given a PERSON Element, it translates column names into values for that column.
That's it! You now know how to extract information from XML Documents and present them in Swing components. In the source code provided, you have to run the AddressBookFrame class in order to see the JTable with the XML information in it. You must also be connected to the Internet at the time, since the AddressBook.xml file is downloaded from the beanfactory.com webserver. If you are not connected to the Internet at the time your run this program, it will appear to hangup (it waits for an Internet connection to be made).
Displaying this XML Document using a Servlet is very similar to creating a TableModel around it. The init() method of the Servlet can create a Document object from an XML file. Then the doGet() method simply has to extract all the values for every column of every row in the Document (using the XmlUtil class) and display a HTML table from it. You can learn more about Servlets in the Java Servlet Programming book.
The following is a listing of the AddressBookServlet.java (for the IBM Parser) which displays this information to a browser. Most of the code here generates the HTML. The actual Document parsing is the same as in the TableModel.
returns a Document in table format.
Create a DOM from an XML document when the servlet starts up.
To run this servlet, place the AddressBookServlet.class and XmlUtils.class in the servlet class folder of your servlet engine and access AddressBookServlet using a web browser.
To run the Swing JTable program, you can type "java AddressBookFrame" at the command prompt. Make sure that you have Java2 (or JDK1.2) installed on your machine because it will not work with JDK1.1. Also, please make sure that you are connected to the Internet at the time because the programs need to access AddressBook.xml from the website.
To run the Servlet, place the AddressBookServlet.class and XmlUtils.class in your servlet folder, and start your servlet engine. You can access the Servlet from your web browser by using a URL like eg: http://localhost/servlet/AddressBookServlet.
Here is older code using an old Sun parser – sun.zip (it should be pretty easy to swap the Sun parser instantiation with the JDOM parser).
I hope you enjoyed this tutorial, I have lots more XML and Java related tutorials on this site.
You can download JDOM here.
Details on instantiating DOM objects using JDOM are provided here. You can learn more about JDOM in the Java and XML book.
This is a good site to learn about Sun's parser and also about how to do elementary things like use SAX and DOM. It also has a nice glossary of terms. After visiting this site and learning everything on it, the content on developerlife.com (which involves real-world application of this technology) will make more sense 😁.
This is not useful for parsing or generating XML documents with Java. This specification lists all the rules that apply to a well formed XML document. This document is only good for specific rules about the syntax of XML documents.
This is very useful for parsing and generating XML documents using Java. All these interfaces are available in Java (for both the Sun and IBM parsers). The documentation for this IDL was used to create the documentation for the IBM and Sun parser's source code. This documentation is more detailed than the javadoc generated documentation for the Java interfaces in the org.w3c.dom package.
Jon Bosak, who is on the chair of the W3C XML Working Group, does a great job of describing what kinds of products and services can be made possible from the union of Java and XML.
This is David Megginson's website documenting the SAX 1.0 API. It is short and to the point. If you want to learn about SAX 1.0 I recommend reading my SAX Tutorial 😁 though .