FileDocCategorySizeDatePackage
LibraryDOMCreator.javaAPI DocExample5497Sun Sep 02 14:59:02 BST 2001chap1

LibraryDOMCreator.java

package chap1;

import java.io.*;
import java.util.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


/**
 * An example from Chapter 1. Creates the library XML file using the
 * DOM API.
 */
public class LibraryDOMCreator {

    /**
     * Create a new DOM org.w3c.dom.Document object from the specified
     * Library object.
     *
     * @param library an application defined class that
     * provides a list of publishers and books.
     * @return a new DOM Document.
     */
    public Document createDocument(Library library)
            throws javax.xml.parsers.ParserConfigurationException {
        // Use Sun's Java API for XML Parsing to create the
        // DOM Document
        javax.xml.parsers.DocumentBuilderFactory dbf =
            javax.xml.parsers.DocumentBuilderFactory.newInstance();
        javax.xml.parsers.DocumentBuilder docBuilder =
            dbf.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        // NOTE: DOM does not provide a factory method for creating:
        //   <!DOCTYPE library SYSTEM "library.dtd">
        // Apache's Xerces provides the createDocumentType method
        // on their DocumentImpl class for doing this.  Not used here.

        // create the <library> document root element
        Element root = doc.createElement("library");
        doc.appendChild(root);

        // add <publisher> children to the <library> element
        Iterator publisherIter = library.getPublishers().iterator();
        while (publisherIter.hasNext()) {
            Publisher pub = (Publisher) publisherIter.next();
            Element pubElem = createPublisherElement(doc, pub);
            root.appendChild(pubElem);
        }

        // now add <book> children to the <library> element
        Iterator bookIter = library.getBooks().iterator();
        while (bookIter.hasNext()) {
            Book book = (Book) bookIter.next();
            Element bookElem = createBookElement(doc, book);
            root.appendChild(bookElem);
        }

        return doc;
    }


    private Element createPublisherElement(Document doc, Publisher pub) {
        Element pubElem = doc.createElement("publisher");

        // set id="oreilly" attribute
        pubElem.setAttribute("id", pub.getId());

        Element name = doc.createElement("name");
        name.appendChild(doc.createTextNode(pub.getName()));
        pubElem.appendChild(name);

        Element street = doc.createElement("street");
        street.appendChild(doc.createTextNode(pub.getStreet()));
        pubElem.appendChild(street);

        Element city = doc.createElement("city");
        city.appendChild(doc.createTextNode(pub.getCity()));
        pubElem.appendChild(city);

        Element state= doc.createElement("state");
        state.appendChild(doc.createTextNode(pub.getState()));
        pubElem.appendChild(state);

        Element postal = doc.createElement("postal");
        postal.appendChild(doc.createTextNode(pub.getPostal()));
        pubElem.appendChild(postal);

        return pubElem;
    }

    private Element createBookElement(Document doc, Book book) {
        Element bookElem = doc.createElement("book");

        bookElem.setAttribute("publisher", book.getPublisher().getId());
        bookElem.setAttribute("isbn", book.getISBN());

        Element edition = doc.createElement("edition");
        edition.appendChild(doc.createTextNode(
                Integer.toString(book.getEdition())));
        bookElem.appendChild(edition);

        Element publicationDate = doc.createElement("publicationDate");
        publicationDate.setAttribute("mm",
                Integer.toString(book.getPublicationMonth()));
        publicationDate.setAttribute("yy",
                Integer.toString(book.getPublicationYear()));
        bookElem.appendChild(publicationDate);

        Element title = doc.createElement("title");
        title.appendChild(doc.createTextNode(book.getTitle()));
        bookElem.appendChild(title);

        Element author = doc.createElement("author");
        author.appendChild(doc.createTextNode(book.getAuthor()));
        bookElem.appendChild(author);

        return bookElem;
    }


    public static void main(String[] args) throws IOException,
            javax.xml.parsers.ParserConfigurationException {
        Library lib = new Library();
        LibraryDOMCreator ldc = new LibraryDOMCreator();
        Document doc = ldc.createDocument(lib);

        // note: this is slightly different than what is shown in the book,
        //       merely because xerces.jar is not included in the download
        //       ZIP file.
        try {
            System.out.println(
                    com.oreilly.javaxslt.util.DOMUtil.domToString(doc));
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        /*
        NOTE: In the book, Xerces is used as shown here:

        // write the Document using Apache Xerces
        // output the Document with UTF-8 encoding; indent each line
        org.apache.xml.serialize.OutputFormat fmt =
            new org.apache.xml.serialize.OutputFormat(doc, "UTF-8", true);
        org.apache.xml.serialize.XMLSerializer serial =
            new org.apache.xml.serialize.XMLSerializer(System.out, fmt);
        serial.serialize(doc.getDocumentElement());
        */
    }
}