Browse DevX
Sign up for e-mail newsletters from DevX


Practical XML for Java Programs : Page 3

When dealing with XML, you need a convenient representation of the XML data in memory. This article offers Java programmers a solution to achieve this goal: an easy-to-use package for handling XML data in Java.





Parsing XML Files
Traditional DOM converts even a simple XML file into a complex, rigid structure in memory. Furthermore, "XML navigation" has its own special language, XPath. Using it, you can browse the data you have just read. You just have to form something that reminds your SQL statements to extract the data you need. Many SQL servers now can return data in XML format, but so what? Do you need one more SQL statement to parse the resultset? A much simpler view of XML does exist though (e.g., XmlTree class in Tomcat 3.3.1).

An XML document is a unidirectional, tree-like structure, with nodes having attributes and leaf nodes having text values. A node's subnodes can be grouped according to their types. In SAX, subnodes are known as kids. Here is an example of how it works:

XmlData project = XmlReader.read(new File("myProject.xml")); String moduleName = "Nails"; for (Iterator i = project.getKid("module", moduleName).getKids("file".iterator();
i.hasNext();) { XmlData fileData = (XmlData)i.next(); System.out.println("Project " + project.getAttribute("id") + ", module " + moduleName + " file " + fileData.getAttribute("id") + " is of type " + fileData.getAttribute("type"); }

In this example, the code read an XML file into an XML data container. Then it retrieved kids of type "file" from the XML data container, which is the kid of type "module" and has an attribute id="Nails". Then it scanned through the collection of such kids and retrieved their attributes.
