Datasheet

35: } catch (IOException ioe) {
36: System.out.println("I/O Error during parsing " +
37: ioe.getMessage());
38: ioe.printStackTrace();
39: }
40: }
41:
The dom2Book function creates the Book object:
42: private static Book dom2Book(Document d) throws SAXException {
43: NodeList nl = d.getElementsByTagNameNS(bookNS, "book");
44: Element bookElt = null;
45: Book book = null;
46: try {
47: if (nl.getLength() > 0) {
48: bookElt = (Element) nl.item(0);
49: book = new Book();
50: } else
51: throw new SAXException("No book element found");
52: } catch (ClassCastException cce) {
53: throw new SAXException("No book element found");
54: }
55:
In lines 43-54, you use the namespace-aware method getElementsByTagNameNS (as opposed to the
non-namespace-aware getElementsByTagName) to find the root book element in the XML file. You check
the resulting NodeList to make sure a book element was found before constructing a new Book instance.
Once you have the book element, you iterate through all the children of the book. These nodes in the
DOM tree correspond to the child elements of the book element in the XML document. As you encounter
each child element node, you need to get the text content for that element and call the appropriate Book
setter. In the DOM, getting the text content for an element node is a little laborious. If an element node
has text content, the element node has one or more children that are text nodes. The DOM provides a
method called normalize that collapses multiple text nodes into a single text node where possible (nor-
malize also removes empty text nodes where possible). Each time you process one of the children of the
book element, you call normalize to collect all the text nodes and store the text content in the String text.
Then you compare the tag name of the element you’re processing and call the appropriate setter method.
As with SAX, you have to convert the text to an integer for the Book’s year field:
56: for (Node child = bookElt.getFirstChild();
57: child != null;
58: child = child.getNextSibling()) {
59: if (child.getNodeType() != Node.ELEMENT_NODE)
60: continue;
61: Element e = (Element) child;
62: e.normalize();
63: String text = e.getFirstChild().getNodeValue();
64:
65: if (e.getTagName().equals("title")) {
66: book.setTitle(text);
67: } else if (e.getTagName().equals("author")) {
14
Chapter 1
01 543555 Ch01.qxd 11/5/03 9:40 AM Page 14