BUILDING XML- BASED APPLICATIONS Parsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting – Modeling Databases in XML Prepared By: Prabu.U
Parsing XML Using Document Object Model  What Is DOM, Anyway?  What DOM Is Not ?  Why Do I Need DOM?  Disadvantages of Using DOM  DOM Levels  DOM Core  DOM Traversal and Range  Other DOM Implementations  Java Architecture for XML Binding (JAXB) Prepared By: Prabu.U
What Is DOM, Anyway?  The Document Object Model (DOM) provides a way of representing an XML document in memory so that it can be manipulated by your software.  DOM is a standard application programming interface (API) that makes it easy for programmers to access elements and delete, add, or edit content and attributes.  The DOM interfaces are defined independent of any particular programming language.  DOM code can be written in any programming language, such as Java, ECMAScript (a standardized version of JavaScript), or C++. Prepared By: Prabu.U
What DOM Is Not ?  DOM is not a mechanism for persisting, or storing, objects as XML documents. Think of it the other way: DOM is an object model for representing XML documents in your code.  DOM is not a set of data structures; rather it is an object model describing XML documents.  DOM does not specify what information in a document is relevant or how information should be structured.  DOM has nothing to do with COM, CORBA, or other technologies that include the words object model. Prepared By: Prabu.U
Why Do I Need DOM?  The main reason for using DOM is to create or modify an XML document programmatically.  If you want to create a document, you start by creating a root element and then add attributes, content, sub-elements, and so on.  Once you are finished, you can write the document out to disk or send it over a network.  The output looks just like an XML document prepared in a text editor or XML tool. Prepared By: Prabu.U
Why Do I Need DOM?  If you want to modify an existing XML document, you can read it in from a file or other I/O source.  The entire document is read into memory all at once, so you can change any part of it at any time.  The representation in memory is a tree structure that starts with a root element that contains attributes, content, and sub-elements.  You can traverse this tree, search for a specific node, and change its attributes or data.  You can also add attributes or elements anywhere in the tree, as long as you don’t violate the rules of a well-formed document. Prepared By: Prabu.U
Disadvantages of Using DOM  One of the big issues is that DOM can be memory intensive.  When an XML document is loaded, the entire document is read in at once. A large document will require a large amount of memory to represent it.  Some have argued that the DOM API is too complex. Although this is somewhat subjective, it is true that DOM is not practical for small devices such as PDAs and cellular phones.  With the rapid proliferation of these devices and demand for greater functionality, XML will very likely play a role in this market. Prepared By: Prabu.U
DOM Core <purchase-order> <customer>James Bond</customer> <merchant>Spies R Us</merchant> <items> <item>Night vision camera</item> <item>Vibrating massager</item> </items> </purchase-order> Prepared By: Prabu.U
DOM Core Prepared By: Prabu.U
DOM Interface Relationships Prepared By: Prabu.U
Extended Interfaces Prepared By: Prabu.U
// Print the element names using getNodeName() from the Node interface. import org.w3c.dom.*; import javax.xml.parsers.*; public class SimpleWalker { protected DocumentBuilder docBuilder; protected Element root; public SimpleWalker() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); docBuilder = dbf.newDocumentBuilder(); DOMImplementation domImp = docBuilder.getDOMImplementation(); if (domImp.hasFeature(“XML”, “2.0”)) { System.out.println(“Parser supports extended interfaces”); } } Prepared By: Prabu.U
public void parse(String fileName) throws Exception { Document doc = docBuilder.parse(new FileInputStream(fileName)); root = doc.getDocumentElement(); System.out.println(“Root element is “ + root.getNodeName()); } public void printAllElements() throws Exception { printElement(“”, root); } Prepared By: Prabu.U
public void printElement(String indent, Node aNode) { System.out.println(indent + “<” + aNode.getNodeName() + “>”); Node child = aNode.getFirstChild(); while (child != null) { printElement(indent + “t”, child); child = child.getNextSibling(); } System.out.println(indent + “</” + aNode.getNodeName() + “>”); } Prepared By: Prabu.U
public static void main(String args[]) throws Exception { SimpleWalker sw = new SimpleWalker(); sw.parse(args[0]); sw.printAllElements(); } } // class SimpleWalker Prepared By: Prabu.U
library.xml <?xml version=”1.0” encoding=”UTF-8”?> <library> <fiction> <book>Moby Dick</book> <book>The Last Trail</book> </fiction> <biography> <book>The Last Lion, Winston Spencer Churchill</book> </biography> </library> Prepared By: Prabu.U
Output from SimpleWalker <library> <#text> </#text> <fiction> <#text></#text> <book> <#text> </#text> </book> <#text> </#text> <book> <#text> </#text> </book> <#text> </#text> </fiction> <#text> </#text> <biography> <#text> </#text> <book> <#text> </#text> </book> <#text> </#text> </biography> <#text> </#text> </library> Prepared By: Prabu.U
If we call getNodeName() on a text node, we get #text, not the text itself. If we want to get the text, we must determine whether we have a text node and then call getNodeValue(). Prepared By: Prabu.U
public void printElement(String indent, Node aNode) { if (aNode.getNodeType() == Node.TEXT_NODE) { System.out.println(indent + aNode.getNodeValue()); } else { System.out.println(indent + “<” + aNode.getNodeName() + “>”); Node child = aNode.getFirstChild(); while (child != null) { printElement(indent + “t”, child); child = child.getNextSibling(); } System.out.println(indent + “</” + aNode.getNodeName() + “>”); } } Prepared By: Prabu.U
Output After printElement() Modification <library> <fiction> <book> Moby Dick </book> <book> The Last Trail </book> </fiction> <biography> <book> The Last Lion, Winston Spencer Churchill </book> </biography> </library> Prepared By: Prabu.U
DOM Traversal and Range  Traversal and range are features added in DOM Level 2.  They are supported by Apache Xerces.  You can determine whether traversal is supported by calling the hasFeature() method of the DOMImplementation interface.  For traversal, you can use the arguments “Traversal” and “2.0” for the feature and version parameters of the hasFeature() method. Prepared By: Prabu.U
Traversal  Traversal is a convenient way to walk through a DOM tree and select specific nodes.  This is useful when you want to find certain elements and perform operations on them. Prepared By: Prabu.U
Traversal Interfaces Prepared By: Prabu.U
Traversal <?xml version=”1.0” encoding=”UTF-8”?> <library> <fiction> <book>Moby Dick</book> <book>The Last Trail</book> </fiction> <biography> <book>The Last Lion, Winston Spencer Churchill</book> </biography> </library> Prepared By: Prabu.U
Traversal IteratorApp.java public void parse(String fileName) throws Exception { document = docBuilder.parse(new FileInputStream(fileName)); root = document.getDocumentElement(); System.out.println(“Root element is “ + root.getNodeName()); } Prepared By: Prabu.U
Traversal public void iterate() { NodeIterator iter = ((DocumentTraversal)document).createNodeIterator( root, NodeFilter.SHOW_ELEMENT, new NameNodeFilter(“book”), true); Node n = iter.nextNode(); while (n != null) { System.out.println(n.getFirstChild().getNodeValue()); n = iter.nextNode(); } } Prepared By: Prabu.U
Traversal OUTPUT: Root element is library Moby Dick The Last Trail The Last Lion, Winston Spencer Churchill Prepared By: Prabu.U
Range  Range interfaces provide a convenient way to select, delete, extract, and insert content.  You can determine whether range is supported by calling the hasFeature(...) method of the DOMImplementation interface.  You can use the arguments “Range” and “2.0” for feature and version.  There are a number of applications for which the range interfaces are useful. Prepared By: Prabu.U
Range Interfaces Prepared By: Prabu.U
Other DOM Implementations  For a variety of reasons, some have argued that DOM as specified by the W3C is not the best way to go.  One reason is that it’s too complex. In this case, JDOM has appeared as an alternative.  Another reason is that DOM takes too much memory and is not practical for resource-constrained devices such as PDAs and cellular phones. Prepared By: Prabu.U
JDOM  JDOM is not an acronym. It was originally developed as an open- source API for XML but has been accepted by the Java Community Process (JCP JSR-102).  The home of JDOM is www.jdom.org.  JDOM was designed specifically for Java. In contrast, DOM is purely an interface specification independent of any language.  For example, a Java parser can leverage standard Java types and collections, such as the String class and the Collections API. Prepared By: Prabu.U
Here are some of the guiding principles of JDOM:  JDOM should be straightforward for Java programmers.  JDOM should support easy and efficient document modification.  JDOM should hide the complexities of XML wherever possible, while remaining true to the XML specification.  JDOM should integrate with DOM and SAX.  JDOM should be lightweight and fast.  JDOM should solve 80 percent (or more) of Java/XML problems with 20 percent (or less) of the effort when compare with DOM. Prepared By: Prabu.U
Java Architecture for XML Binding (JAXB) Modeling Databases in XML  In the JAXB framework, we can parse XML documents into a suitable Java object. This technique is referred to as unmarshaling.  The JAXB framework also provides the capability to generate XML documents from Java objects, which is referred to as marshaling. Prepared By: Prabu.U
JAXB (Java API for XML Binding) Solution The following steps are followed 1. Review the database schema. 2. Construct the desired XML document. 3. Define a schema for the XML document. 4. Create the JAXB binding schema. 5. Generate the JAXB classes based on the schema. 6. Develop a Data Access Object (DAO). 7. Develop a servlet for HTTP access.. Prepared By: Prabu.U
Defining a Schema for the XML Document rental_property.dtd Prepared By: Prabu.U
Creating the JAXB Binding Schema rental_property.xjs (for XML Java schema) Prepared By: Prabu.U
Generating the JAXB Classes Based on Schemas Prepared By: Prabu.U
Generating the JAXB Classes Based on Schemas The following files are generated: RentalPropertyList.java: This file models the <rental_property_list> element. RentalProperty.java: This file models the <rental_property> element. Address.java: This file models the <address> subelement. Contact.java: This file models the <contact> subelement. Prepared By: Prabu.U
Developing a Data Access Object (DAO) A Data Access Object (DAO) provides access to the backend database. The goal of the DAO design pattern is to provide a higher level of abstraction for database access. Prepared By: Prabu.U
Parsing XML Using Simple API for XML (SAX) What Is SAX, Anyway? What SAX Is Not ? Why Do I Need SAX? SAX vs. DOM Disadvantages SAX Versions SAX Basics Working with SAX Prepared By: Prabu.U
What Is SAX, Anyway?  SAX is an API that can be used to parse XML documents.  A parser is a program that reads data, a character at a time and returns manageable pieces of data.  For example, a parser for the English language might break up a document into paragraphs, words, and punctuation.  In the case of XML, the important pieces of data include elements, attributes, text, and so on. This is what SAX does. Prepared By: Prabu.U
What Is SAX, Anyway?  SAX provides a framework for defining event listeners, or handlers. These handlers are written by developers interested in parsing documents with a known structure.  The handlers are registered with the SAX framework in order to receive events.  Events can include start of document, start of element, end of element, and so on.  The handlers contain a number of methods that will be called in response to these events.  Once the handlers are defined and registered, an input source can be specified and parsing can begin. Prepared By: Prabu.U
What SAX Is Not ?  SAX by itself is just an API, and a number of implementations are available from many of the familiar sources.  The most commonly used parsers are Xerces from the Apache XML project and Java API for XML Processing (JAXP) from Sun Microsystems.  SAX was originally developed in Java, but similar implementations are available in other languages as well. There are implementations for Perl, Python, and C++, for example. Prepared By: Prabu.U
Why Do I Need SAX?  If a tool or a standalone program is written to process XML, SAX is a good way to do it.  Many applications today can be customized using an XML file. These files have replaced the traditional “properties” files for reasons of uniformity and richness of expression.  Instead of spending a lot of time writing a parser to read XML files, SAX can be used.  SAX is completely free, so it can be embedded in a larger application without royalty fees or even copyright notices.  Some SAX parsers can validate a document against a Document Type Definition (DTD). Prepared By: Prabu.U
SAX vs. DOM SAX is, in many ways, much simpler than DOM  There is no need to model every possible type of object that can be found in an XML document. This makes the API easy to understand and easier to use.  DOM contains many interfaces, each containing many methods. SAX is comprised of a handful of classes and interfaces.  SAX is a much lower-level API when compared with DOM. For these reasons, SAX parsers tend to be smaller than DOM implementations.  In fact, many DOM implementations use SAX parsers under the hood to read in XML documents. Prepared By: Prabu.U
SAX vs. DOM SAX is an event-based API  Instead of loading an entire document into memory all at once, SAX parsers read documents and notify a client program when elements, text, comments, and other data of interest are found.  SAX parsers send you events continuously, telling you what was found next. Prepared By: Prabu.U
SAX vs. DOM The DOM parses XML in space, whereas SAX parses XML in time  In essence, the DOM parser hands you an entire document and allows you to traverse it any way you like. This can take a lot of memory, so SAX can be significantly more efficient for large documents.  In fact, you can process documents larger than available system memory, but this is not possible with DOM. SAX can also be faster, because you don’t have to wait for the entire document to be loaded. This is especially valuable when reading data over a network. Prepared By: Prabu.U
Disadvantages  SAX is not a perfect solution for all problems. For instance, it can be a bit harder to visualize compared to DOM because it is an event- driven model.  SAX parsing is “single pass,” so you can’t back up to an earlier part of the document any more than you can back up from a serial data stream.  Moreover, you have no random access at all. Handling parent/child relationships can be more challenging as well. Prepared By: Prabu.U
Disadvantages  Another disadvantage is that the current SAX implementations are read-only parsers.  They do not provide the ability to manipulate a document or its structure (this feature may be added in the future).  DOM is the way to go if you want to manipulate a document in memory. Prepared By: Prabu.U
SAX Versions  The first version, SAX 1.0, was released in May 1998.  It provided the basic functionality needed to read elements, attributes, text, and to manage errors.  There was also some DTD support. Prepared By: Prabu.U
SAX Versions  The current version, SAX 2.0, was released two years later in May 2000.  Many of the SAX 2.0 interfaces are departures from SAX 1.0. Older interfaces are included, but deprecated, for backward compatibility.  Adapters are included for using SAX 1.0 parsers with SAX 2.0, and vice versa.  SAX 2.0 also includes support for namespaces and extensibility through features and properties. Documentation is improved as well. Prepared By: Prabu.U
SAX Basics <?xml version=”1.0” encoding=”UTF-8”?> <fiction> <book author=”Herman Melville”>Moby Dick</book> </fiction> Prepared By: Prabu.U
SAX Basics  If you want to parse this document using SAX, you would build a content handler by creating a Java class that implements the ContentHandler interface in the org.xml.sax package.  Once you have a content handler, you simply register it with a SAX XMLReader, set up the input source, and start the parser.  Next, the methods in your content handler will be called when the parser encounters elements, text, and other data. Prepared By: Prabu.U
SAX Basics  Specifically, the events generated will look something like this: start document start element: fiction start element: book (including attributes) characters: Moby Dick end element: book end element: fiction end document Prepared By: Prabu.U
SAX Packages  The SAX 2.0 API is comprised of two standard packages and one extension package.  The standard packages are org.xml.sax and org.xml.helpers.  The org.xml.sax package contains the basic classes, interfaces, and exceptions needed for parsing documents Prepared By: Prabu.U
The org.xml.sax Package Prepared By: Prabu.U
The org.xml.sax Package Prepared By: Prabu.U
The org.xml.sax Package Prepared By: Prabu.U
The org.xml.sax.helpers Package Prepared By: Prabu.U
The org.xml.sax.helpers Package Prepared By: Prabu.U
The org.xml.sax.ext Package Prepared By: Prabu.U
Working with SAX import java.io.*; import org.xml.sax.*; import org.xml.sax.helpers.*; import javax.xml.parsers.*; public class SAXDemo extends DefaultHandler { public void startDocument() { System.out.println(“***Start of Document***”); } public void endDocument() { System.out.println(“***End of Document***”); } public void startElement(String uri, String localName, String qName, Attributes attributes) { public void startElement(String uri, String localName, String qName, Attributes attributes) { System.out.print(“<” + qName); int n = attributes.getLength(); for (int i=0; i<n; i+=1) { System.out.print(“ “ + attributes.getQName(i) + “=’” + attributes.getValue(i) + “‘“); } System.out.println(“>”); } public void characters(char[] ch, int start, int length) { System.out.println(new String(ch, start, length).trim()); } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { System.out.println(“</” + qName + “>”); } Prepared By: Prabu.U
Working with SAX public static void main(String args[]) throws Exception { if (args.length != 1) { System.err.println(“Usage: java SAXDemo <xml- file>”); System.exit(1); } SAXDemo handler = new SAXDemo(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(new File(args[0]), handler); } } Prepared By: Prabu.U
The ContentHandler Methods Prepared By: Prabu.U
The ContentHandler Methods Prepared By: Prabu.U
library.xml <?xml version=”1.0” encoding=”UTF-8”?> <!DOCTYPE library SYSTEM “library.dtd”> <library> <fiction> <book author=”Herman Melville”>Moby Dick</book> <book author=”Zane Grey”>The Last Trail</book> </fiction> <biography> <book author=”William Manchester”> The Last Lion, Winston Spencer Churchill </book> </biography> <science> <book author=”Hecht, Zajac”>Optics</book> </science> </library> Prepared By: Prabu.U
Output from SAXDemo ***Start of Document*** <library> <fiction> <book author=’Herman Melville’> Moby Dick </book> <book author=’Zane Grey’> The Last Trail </book> </fiction> <biography> <book author=’William Manchester’> The Last Lion, Winston Spencer Churchill </book> </biography> <science> <book author=’Hecht, Zajac’> Optics </book> </science> </library> ***End of Document*** Prepared By: Prabu.U
The ErrorHandler Methods Prepared By: Prabu.U
The LexicalHandler Methods Prepared By: Prabu.U
XML Transformation and XSL  XSL Technologies  XSLT for Document Publishing  XSL for Business-to-Business (B2B) Communication  XSL Formatting Objects  Web Application Integration: Java Servlets, XSLT, and XSL-FO Prepared By: Prabu.U
XSL Technologies  XSL has two independent languages:  The XSL Transformation Language (XSLT)  The XSL Formatting Object Language (XSL-FO)  XSLT is used to convert an XML document to another format.  XSL-FO provides a way of describing the presentation of an XML document.  Both technologies use a supporting XML technology, XPath. Prepared By: Prabu.U
XSLT for Document Publishing  XSL technology has an important role in the field of document publishing.  Imagine, for example, that we have an XML document for a list of books.  We would like to publish this document in various formats.  Using XSL, we can convert the book list to an HTML file, PDF document, or other format.  The key to this example is the XML document, which serves as a single data source Prepared By: Prabu.U
XSLT for Document Publishing  By applying an XSL style sheet, we render a new view of the data.  The development of multiple style sheets allows us to have multiple views of the same data.  This approach provides a clean separation of the data (the XML document) and the view (the XSL style sheet).  We can also extend this example to support wireless Internet clients.  A growing number of mobile phones and PDAs support the Wireless Application Protocol (WAP). Prepared By: Prabu.U
XSLT for Document Publishing  These WAP enabled devices contain a mini browser for rendering Wireless Markup Language (WML) documents.  To support the wireless Internet clients, all we have to do is design an appropriate XSL style sheet to convert the XML document to WML.  No modifications are required to the original XML document. Prepared By: Prabu.U
Publishing documents with XSLT Prepared By: Prabu.U
Sending data to the XSLT processor  XSLT provides the mechanism for converting an XML document to another format.  This is accomplished by applying an XSLT style sheet to the XML document.  The style sheet contains conversion rules for accessing and transforming the input XML document to a different output format.  An XSLT processor is responsible for applying the rules defined in the style sheet to the input XML document. Prepared By: Prabu.U
Sending data to the XSLT processor Prepared By: Prabu.U
Creating the XSL Style Sheet book_view.xsl <?xml version=”1.0”?> <xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0”> <xsl:template match=”/book”> <html><body> <b>Title: </b> <xsl:value-of select=”title” /> <p/> <b>By: </b> <xsl:value-of select=”author” /> <p/> <b>Cost: </b> <xsl:value-of select=”price” /> <p/> <b>Category: </b> <xsl:value-of select=”category” /> <p/> <b>Description</b> <p/> <i><xsl:value-of select=”summary” /></i> </body></html> </xsl:template> </xsl:stylesheet> Prepared By: Prabu.U
Creating the XML Document <?xml version=”1.0”?> <book> <author>Michael Daconta et al</author> <title>XML Development with Java 2</title> <category>Java</category> <price currency=”USD”>44.99</price> <summary> XML Development with Java 2 provides the information and techniques a Java developer will need to integrate XML into Java- based applications. </summary> </book> Prepared By: Prabu.U
Getting Started with XSLT Prepared By: Prabu.U
The Missing Piece: The XSLT Processor Prepared By: Prabu.U
 Two techniques are available for performing the XSLT processing: client-side processing and server-side processing.  Client-side XSLT processing commonly occurs in a Web browser. The Web browser includes an XSLT processor and retrieves the XML document and XSL style sheet.  The client-side technique offloads the XSLT processing to the client machine.  This minimizes the workload on the Web server. However, the disadvantage is that the Web browser must provide XSLT support. Prepared By: Prabu.U
 At the time of this writing, Netscape Communicator 6 and Microsoft Internet Explorer 6 support the XSLT 1.0 specification.  Microsoft Internet Explorer 5.x has very limited support for XSLT 1.0. The previous version of the Netscape browser, 4.x, provides no support for XSLT.  The client-side technique is applicable when you’re deploying an application in a controlled environment.  For example, in a corporate environment, the system administrators can install the latest version of the Web browser that conforms to the XSLT 1.0 specification. Prepared By: Prabu.U
Prepared By: Prabu.U
 Server-side XSLT processing occurs on the Web server or application server.  A serverside process such as an Active Server Page (ASP), JavaServer Page (JSP), or Java servlet will retrieve the XML document and XSL style sheet and pass them to an XSLT processor.  The output of the XSLT processor is sent to the client Web browser for presentation.  The output is generally a markup language, such as HTML, that is understood by the client browser. Prepared By: Prabu.U
Prepared By: Prabu.U
Implementing Client-Side XSLT Processing book.xml <?xml version=”1.0”?> <?xml-stylesheet type=”text/xsl” href=”book_view.xsl”?> <book> <author>Michael Daconta et al</author> <title>XML Development with Java 2</title> <category>Java</category> <price currency=”USD”>44.99</price> <summary> XML Development with Java 2 provides the information and techniques a Java developer will need to integrate XML into Java-based applications. </summary> </book> Prepared By: Prabu.U
book_view.xsl <?xml version=”1.0”?> <xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0”> <xsl:template match=”/book”> <html><body> <b>Title: </b> <xsl:value-of select=”title” /> <p/> <b>By: </b> <xsl:value-of select=”author” /> <p/> <b>Cost: </b> <xsl:value-of select=”price” /> <p/> <b>Category: </b> <xsl:value-of select=”category” /> <p/> <b>Description</b> <p/> <i><xsl:value-of select=”summary” /></i> </body></html> </xsl:template> </xsl:stylesheet> Prepared By: Prabu.U
XSLT rendered in a Web browser Prepared By: Prabu.U
Implementing Server-Side XSLT Processing  A number of server-side technologies are available, including Common Gateway Interface (CGI), ColdFusion, Hypertext Processor (PHP), and so on.  Here focuses on server-side processing with Microsoft’s Active Server Pages (ASP) and Sun Microsystem’s JavaServer Pages (JSP). Prepared By: Prabu.U
ASP: Server-Side XSLT Processing  In order to develop using ASP, you will need the IIS Web server and the latest version of the Microsoft XML parser. The required components are listed below.  Microsoft IIS Web Server 5.0. This version of IIS is included with Microsoft Windows 2000 Professional. You can also use IIS 4.0 or Personal Web Server (PWS); however, you will have to install the Windows NT Option Pack 4. Refer to Microsoft’s Web site for details on adding ASP support to IIS 4.0 and PWS.  Microsoft XML Parser 3.0. If you have IE 6 installed on your server machine, then MS XML Parser 3.0 is included. The MS XML Parser 3.0 is also available as a separate download from http://msdn.microsoft.com. Prepared By: Prabu.U
book_test.asp <%@ Language=VBScript %> <% set xml = Server.CreateObject(“Microsoft.XMLDOM”) xml.load(Server.MapPath(“book.xml”)) set xsl = Server.CreateObject(“Microsoft.XMLDOM”) xsl.load(Server.MapPath(“book_view.xsl”)) Response.Write(xml.transformNode(xsl)) %> Prepared By: Prabu.U
Prepared By: Prabu.U
JSP: Server-Side XSLT Processing  Sun Microsystems provides a server-side technology that is very similar to ASP.  Of course, the server-side scripting is accomplished in Java. In order to perform the serverside processing with JSP, you will need to install the Java Software Development Kit (SDK) along with a compliant JSP server container. Here’s a list of required components: Prepared By: Prabu.U
JSP: Server-Side XSLT Processing  Sun Microsystems’ Software Development Kit (SDK) 1.3 (or higher). The SDK is available at Sun’s Web site, http://java.sun.com/j2se. Follow the installation instructions provided with the SDK.  Apache Tomcat Server 4. Apache Tomcat 4 is the official reference implementation for JSP 1.2 and Java Servlets 2.3. If your application server already supports JSP 1.1 or higher, there is no requirement to install Tomcat. Apache Tomcat 4 is available from the Apache Web site, http://jakarta.apache.org/tomcat. Prepared By: Prabu.U
book_test.jsp <%@ taglib uri=”http://jakarta.apache.org/taglibs/xsl-1.0” prefix=”jakarta” %> <jakarta:apply xml=”book.xml” xsl=”book_view.xsl” /> Prepared By: Prabu.U
XSL for Business-to-Business (B2B) Communication  The process of exchanging data between two different companies.  Developers can leverage XML to describe the data in a vendor- independent fashion.  In the ideal case, both companies will agree upon a standard vocabulary for describing the data using a DTD or schema.  The vocabulary is composed of the XML element names used in the XML document.  However, in certain cases one of the companies might like to use a different vocabulary. This is where XSL enters the picture. Prepared By: Prabu.U
Prepared By: Prabu.U
XSL for Business-to-Business (B2B) Communication  The example describes a B2B scenario between a training company, Hot Shot Training, and a software development company, AcmeSoft.  The computer training company maintains a database for the students that have attended its courses.  The training company has developed an XML application that produces the list of students for a given class. Prepared By: Prabu.U
 The XML application at the training company is accessible using the HTTP protocol.  The first step is to request the XML document from the training company.  In step 2, the XML document is retrieved.  In step 3, the document is transformed using the supplied XSLT style sheet.  Finally, the desired output document is produced in step 4. Prepared By: Prabu.U
<?xml version=”1.0”?> <trainingclass> <title>J2EE Essentials</title> <start_date>24 Sep 2001</start_date> <end_date>28 Sep 2001</end_date> <location>Philadelphia, PA</location> <student> <first_name>Riley</first_name> <last_name>Scott</last_name> <email>riley@acmesoft.web</email> </student> <student> <first_name>Torrance</first_name> <last_name>Lee</last_name> <email>torrance.lee@acmesoft.web</email> </student> </trainingclass> Prepared By: Prabu.U
<?xml version=”1.0”?> <employeelist> <course_title>J2EE Essentials</course_title> <course_date start=”24 Sep 2001” end=”28 Sep 2001” /> <location>Philadelphia, PA</location> <employee> <name> <first>Riley</first> <last>Scott</last> </name> <email>riley.scott@acmesoft.web</email> </employee> <employee> <name> <first>Torrance</first> <last>Lee</last> </name> <email>torrance.lee@acmesoft.web</email> </employee> </employeelist> Prepared By: Prabu.U
Creating the XSL Style Sheet  The XSL style sheet will contain the template for the <employeelist> document, and the XSL elements will be leveraged to retrieve the data from the <trainingclass> document.  The transformation is fairly straightforward, except for one area. The training company describes the date for the class using the elements <start_date> and <end_date>, as shown here: <start_date>24 Sep 2001</start_date> <end_date>28 Sep 2001</end_date> Prepared By: Prabu.U
Creating the XSL Style Sheet  AcmeSoft stores the date as a single element with two attributes for the start and end: <course_date start=”24 Sep 2001” end=”28 Sep 2001” /> Prepared By: Prabu.U
Creating the XSL Style Sheet  In this case, <xsl:attribute> can be used to create attributes for <course_date>: <course_date> <xsl:attribute name=”start”> <xsl:value-of select=”start_date”/> </xsl:attribute> <xsl:attribute name=”end”> <xsl:value-of select=”end_date”/> </xsl:attribute> </course_date> Prepared By: Prabu.U
train2employee.xsl <?xml version=”1.0”?> <xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0”> <xsl:template match=”/trainingclass”> <employeelist> <course_title><xsl:value-of select=”title” /></course_title> <course_date> <xsl:attribute name=”start”> <xsl:value-of select=”start_date”/> </xsl:attribute> <xsl:attribute name=”end”> <xsl:value-of select=”end_date”/> </xsl:attribute> </course_date> <location><xsl:value-of select=”location” /></location> Prepared By: Prabu.U
<!-- Perform a loop for each student in the training class --> <xsl:for-each select=”student” <employee> <name> <first><xsl:value-of select=”first_name”/></first> <last><xsl:value-of select=”last_name”/></last> </name> <email><xsl:value-of select=”email”/></email> </employee> </xsl:for-each> </employeelist> </xsl:template> </xsl:stylesheet> Prepared By: Prabu.U
XSL Formatting Objects XSL-FO Formatting Engines Prepared By: Prabu.U
Basic Document Structure  The following code snippet shows the basic document setup for XSL-FO: <?xml version=”1.0” encoding=”utf-8”?> <fo:root xmlns:fo=”http://www.w3.org/1999/XSL/Format”> <!-- layout master set --> <!-- page masters: size and layout --> <!-- page sequences and content --> </fo:root> Prepared By: Prabu.U
Basic Document Structure  The element <fo:root> is the root element for the XSL-FO document. An XSL-FO document can contain the following components: • Page master • Page master set • Page sequences Prepared By: Prabu.U
Page Master: <fo:page-master>  The <fo:simple-page-master> element defines the layout of a page. The following code snippet describes a U.S. letter: <fo:simple-page-master master-name=”simple” page-height=”11in” page-width=”8.5in” margin-top=”1in” margin-bottom=”1in” margin-left=”1.25in” margin-right=”1.25in”> </fo:simple-page-master> Prepared By: Prabu.U
Components of the page master Prepared By: Prabu.U
Five regions of a page Prepared By: Prabu.U
Five regions of a page The following example defines the dimensions for <fo:region- body>, <fo:regionbefore>, and <fo:region-after>: <fo:simple-page-master master-name=”simple” page-height=”11in” page-width=”8.5in”> <fo:region-body margin-top=”0.5in”/> <fo:region-before extent=”0.5in”/> <fo:region-after extent=”0.5in”/> </fo:simple-page-master> Prepared By: Prabu.U
Page Master Set: <fo:page-master-set> <fo:layout-master-set> <fo:simple-page-master master-name=”simple” page-height=”11in” page-width=”8.5in” margin-top=”1in” margin-bottom=”1in” margin-left=”1.25in” margin-right=”1.25in”> <fo:region-body margin-top=”0.5in”/> <fo:region-before extent=”3cm”/> <fo:region-after extent=”1.5cm”/> </fo:simple-page-master> </fo:layout-master-set> Prepared By: Prabu.U
Page Master Set: <fo:page-master-set>  A document can be composed of multiple pages, each with its own dimensions. The page master set refers to the collection of page masters.  In the following code example, a page master set is defined that contains one page set: Prepared By: Prabu.U
<fo:layout-master-set> <fo:simple-page-master master-name=”simple” page-height=”11in” page-width=”8.5in” margin-top=”1in” margin-bottom=”1in” margin-left=”1.25in” margin-right=”1.25in”> <fo:region-body margin-top=”0.5in”/> <fo:region-before extent=”3cm”/> <fo:region-after extent=”1.5cm”/> </fo:simple-page-master> </fo:layout-master-set> Prepared By: Prabu.U
Page Sequences: <fo:page-sequence>  A page sequence defines a series of printed pages. Each page sequence refers to a page master for its dimensions.  The page sequence contains the actual content for the document.  The <fo:page-sequence> element contains <fo:static-content> and <fo:flow> elements. Prepared By: Prabu.U
Page Sequences: <fo:page-sequence>  The <fo:static-content> element is used for page headers and footers.  For example, we can define a header for the company name and page number, and this information will appear on every page.  The <fo:flow> element contains a collection of text blocks. The <fo:flow> element is similar to a collection of paragraphs. Prepared By: Prabu.U
Page Sequences: <fo:page-sequence>  A body of text is defined using the <fo:block> element.  The <fo:block> element is a child element of <fo:flow>. The <fo:block> element contains free-flowing text that will wrap to the next line in a document if it overflows. Prepared By: Prabu.U
simple.fo <!-- page sequences and content --> <fo:page-sequence master-name=”simple”> <fo:flow flow-name=”xsl-region-body”> <!-- this defines a level 1 heading with orange background --> <fo:block font-size=”18pt” font-family=”sans-serif” line-height=”24pt” space-after.optimum=”15pt” background-color=”orange” color=”white” text-align=”center” padding-top=”3pt”> Ez Books Online </fo:block> Prepared By: Prabu.U
<!-- Paragraph that contains info about the company --> <fo:block font-size=”12pt” font-family=”sans-serif” line-height=”15pt” space-after.optimum=”14pt” text-align=”justify”> Welcome to Ez Books Online, the world’s smallest online book store. Our company’s mission is to sell books on Java, Thrillers and Romance. We have something for everyone...so we think. Feel free to browse our catalog and if you find a book of interest then send us an e-mail. Thanks for visiting! </fo:block> </fo:flow> </fo:page-sequence> Prepared By: Prabu.U
Page Headers and Footers header_footer.fo <fo:page-sequence master-name=”simple”> <!-- header --> <fo:static-content flow-name=”xsl-region-before”> <fo:block text-align=”end” font-size=”10pt” font-family=”serif” line-height=”14pt” > Ez Books Catalog - page <fo:page-number/> </fo:block> </fo:static-content> Prepared By: Prabu.U
<!-- footer --> <fo:static-content flow-name=”xsl-region-after”> <fo:block text-align=”center” font-size=”10pt” font-family=”serif” line-height=”14pt” > Visit our website http://www.ezbooks.web </fo:block> </fo:static-content> Prepared By: Prabu.U
<!-- body --> <fo:flow flow-name=”xsl-region-body”> <!-- this defines a level 1 heading with orange background --> <fo:block font-size=”18pt” font-family=”sans-serif” line-height=”24pt” space-after.optimum=”15pt” background-color=”orange” color=”white” text-align=”center” padding-top=”3pt”> Ez Books Online </fo:block> Prepared By: Prabu.U
<!-- insert page break for second page --> <fo:block break-before=”page”> A page break is inserted before this block. Notice we have the headers and footers in place. This was accomplished with the fo-static-content elements. We can continue on...business as usual. </fo:block> Prepared By: Prabu.U
<!-- insert page break for third page --> <fo:block break-before=”page”> Information on our third page. Again...notice the page number is incrementing for us...automagically. Wouldn’t it be great to generate this XSL-FO page dynamically? Hold tight, dynamic demos are coming up! </fo:block> Prepared By: Prabu.U
Graphics  XSL-FO also allows for the insertion of external graphic images. The graphic formats supported are dependent on the XSL-FO formatting engine.  The Apache-FOP formatting engine supports the popular graphics formats: GIF, JPEG, and BMP. Prepared By: Prabu.U
Graphics The following code fragment inserts the image smiley.jpg: <fo:block text-align=”center”> <fo:external-graphic src=”smiley.jpg” width=”200px” height=”200px”/> </fo:block> Prepared By: Prabu.U
Tables  XSL-FO has rich support for structuring tabular data.  In fact, there are many similarities between HTML tables and XSL-FO tables. Prepared By: Prabu.U
Comparing HTML Table Elements and XSL-FO Table Elements Prepared By: Prabu.U
<!-- table start --> <fo:table> <!-- define column widths --> <fo:table-column column-width=”120pt”/> <fo:table-column column-width=”200pt”/> <fo:table-column column-width=”80pt”/> Prepared By: Prabu.U
<fo:table-header> <fo:table-row> <fo:table-cell> <fo:block font-weight=”bold”>Author</fo:block> </fo:table-cell> <fo:table-cell> <fo:block font-weight=”bold”>Title</fo:block> </fo:table-cell> <fo:table-cell> <fo:block font-weight=”bold”>Price (USD)</fo:block> </fo:table-cell> </fo:table-row> </fo:table-header> Prepared By: Prabu.U
<fo:table-body> <fo:table-row> <fo:table-cell> <fo:block>Michael Daconta</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>XML Development with Java 2</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>37.99</fo:block> </fo:table-cell> </fo:table-row> Prepared By: Prabu.U
<fo:table-row> <fo:table-cell> <fo:block>E. Lynn Harris</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>Any Way The Wind Blows</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>19.95</fo:block> </fo:table-cell> </fo:table-row> Prepared By: Prabu.U
<fo:table-row> <fo:table-cell> <fo:block>Tom Clancy</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>Executive Orders</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>7.99</fo:block> </fo:table-cell> </fo:table-row> </fo:table-body> </fo:table> <!-- table end --> Prepared By: Prabu.U
Prepared By: Prabu.U
Modeling Databases in XML Prepared By: Prabu.U
1. Review the database schema. 2. Construct the desired XML document. 3. Define a schema for the XML document. 4. Create the JAXB binding schema. 5. Generate the JAXB classes based on the schema. 6. Develop a Data Access Object (DAO). 7. Develop a servlet for HTTP access. JAXB Solution Prepared By: Prabu.U
Reviewing the Database Schema Prepared By: Prabu.U
Reviewing the Database Schema Prepared By: Prabu.U
Constructing the Desired XML Document Prepared By: Prabu.U
Constructing the Desired XML Document Prepared By: Prabu.U
rental_property.dtd <!ELEMENT rental_property_list (rental_property)* > <!ELEMENT rental_property (prop_id, name, address, square_footage, bedrooms, bath, price, contact)> <!ELEMENT prop_id (#PCDATA)> <!ELEMENT name (#PCDATA)> <!ELEMENT address (street, city, state, postal_code)> <!ELEMENT street (#PCDATA)> <!ELEMENT city (#PCDATA)> <!ELEMENT state (#PCDATA)> <!ELEMENT postal_code (#PCDATA)> Defining a Schema for the XML Document Prepared By: Prabu.U
<!ELEMENT square_footage (#PCDATA)> <!ELEMENT bedrooms (#PCDATA)> <!ELEMENT bath (#PCDATA)> <!ELEMENT price (#PCDATA)> <!ELEMENT contact (phone, fax)> <!ELEMENT phone (#PCDATA)> <!ELEMENT fax (#PCDATA)> Defining a Schema for the XML Document Prepared By: Prabu.U
rental_property.xjs <!DOCTYPE xml-java-binding-schema SYSTEM ”http://java.sun.com/dtd/jaxb/1.0- ea/xjs.dtd”> <xml-java-binding-schema version=”1.0-ea”> <options package=”xmlunleashed.ch10.jaxb”/> <element name=”rental_property_list” type=”class” root=”true”> <content property=”list”/> </element> <element name=”square_footage” type=”value” convert=”double”/> <element name=”bedrooms” type=”value” convert=”double”/> <element name=”bath” type=”value” convert=”double”/> <element name=”price” type=”value” convert=”BigDecimal”/> <conversion name=”BigDecimal” type=”java.math.BigDecimal”/> </xml-java-binding-schema> Creating the JAXB Binding Schema Prepared By: Prabu.U
Generating the JAXB Classes Based on Schemas Prepared By: Prabu.U
Developing a Data Access Object (DAO) Prepared By: Prabu.U
RentalPropertyDAO interaction diagram Prepared By: Prabu.U
 A test harness is a small program that tests the basic functionality of the application.  If designed properly, The test harness provides a way of producing predictable results from an application. Creating a Test Harness for RentalPropertyDAO Prepared By: Prabu.U
 The TestApp program will construct the RentalPropertyDAO Data Access Object and then retrieve a list of RentalProperty objects by calling the method getRentalPropertyList().  The XML data is displayed by calling the marshal() method on RentalPropertyList. Creating a Test Harness for RentalPropertyDAO Prepared By: Prabu.U
public class TestApp { protected RentalPropertyDAO myRentalDAO; public TestApp() throws DAOException { myRentalDAO = new RentalPropertyDAO(); } public void process() throws DAOException, IOException { // Get the list of rental properties RentalPropertyList theList = myRentalDAO.getRentalProperties(); // Send the XML data to standard out. theList.marshal(System.out); } Prepared By: Prabu.U
public static void main(String[] args) { try { TestApp myApp = new TestApp(); myApp.process(); } catch (Exception exc) { exc.printStackTrace(); } } Prepared By: Prabu.U
Converting the XML Data to HTML with XSLT Prepared By: Prabu.U
rental_view.xsl <?xml version=”1.0”?> <xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0”> <xsl:template match=”/rental_property_list”> <html><body> <h3>Rental Properties</h3> <hr></hr> <table border=”1” cellpadding=”5”> <tr> <th>Name</th> <th>Street</th> <th>City, State</th> <th>Square Footage</th> <th>Bedrooms</th> <th>Bath</th> <th>Price</th> </tr> Prepared By: Prabu.U
<!— Perform loop for each rental property in the list —> <xsl:for-each select=”rental_property” > <tr> <td> <xsl:value-of select=”name” /> </td> <td> <xsl:value-of select=”address/street” /> </td> <td> <xsl:value-of select=”address/city” />,<xsl:value-of select=”address/state” /> </td> <td> <xsl:value-of select=”square_footage” /> </td> <td> <xsl:value-of select=”bedrooms” /> </td> <td> <xsl:value-of select=”bath” /> </td> <td> $ <xsl:value-of select=”price” /> </td> </tr> </xsl:for-each> </table> </body></html> </xsl:template> </xsl:stylesheet> Prepared By: Prabu.U

Building XML Based Applications

  • 1.
    BUILDING XML- BASED APPLICATIONS ParsingXML – using DOM, SAX – XML Transformation and XSL – XSL Formatting – Modeling Databases in XML Prepared By: Prabu.U
  • 2.
    Parsing XML UsingDocument Object Model  What Is DOM, Anyway?  What DOM Is Not ?  Why Do I Need DOM?  Disadvantages of Using DOM  DOM Levels  DOM Core  DOM Traversal and Range  Other DOM Implementations  Java Architecture for XML Binding (JAXB) Prepared By: Prabu.U
  • 3.
    What Is DOM,Anyway?  The Document Object Model (DOM) provides a way of representing an XML document in memory so that it can be manipulated by your software.  DOM is a standard application programming interface (API) that makes it easy for programmers to access elements and delete, add, or edit content and attributes.  The DOM interfaces are defined independent of any particular programming language.  DOM code can be written in any programming language, such as Java, ECMAScript (a standardized version of JavaScript), or C++. Prepared By: Prabu.U
  • 4.
    What DOM IsNot ?  DOM is not a mechanism for persisting, or storing, objects as XML documents. Think of it the other way: DOM is an object model for representing XML documents in your code.  DOM is not a set of data structures; rather it is an object model describing XML documents.  DOM does not specify what information in a document is relevant or how information should be structured.  DOM has nothing to do with COM, CORBA, or other technologies that include the words object model. Prepared By: Prabu.U
  • 5.
    Why Do INeed DOM?  The main reason for using DOM is to create or modify an XML document programmatically.  If you want to create a document, you start by creating a root element and then add attributes, content, sub-elements, and so on.  Once you are finished, you can write the document out to disk or send it over a network.  The output looks just like an XML document prepared in a text editor or XML tool. Prepared By: Prabu.U
  • 6.
    Why Do INeed DOM?  If you want to modify an existing XML document, you can read it in from a file or other I/O source.  The entire document is read into memory all at once, so you can change any part of it at any time.  The representation in memory is a tree structure that starts with a root element that contains attributes, content, and sub-elements.  You can traverse this tree, search for a specific node, and change its attributes or data.  You can also add attributes or elements anywhere in the tree, as long as you don’t violate the rules of a well-formed document. Prepared By: Prabu.U
  • 7.
    Disadvantages of UsingDOM  One of the big issues is that DOM can be memory intensive.  When an XML document is loaded, the entire document is read in at once. A large document will require a large amount of memory to represent it.  Some have argued that the DOM API is too complex. Although this is somewhat subjective, it is true that DOM is not practical for small devices such as PDAs and cellular phones.  With the rapid proliferation of these devices and demand for greater functionality, XML will very likely play a role in this market. Prepared By: Prabu.U
  • 8.
    DOM Core <purchase-order> <customer>James Bond</customer> <merchant>SpiesR Us</merchant> <items> <item>Night vision camera</item> <item>Vibrating massager</item> </items> </purchase-order> Prepared By: Prabu.U
  • 9.
  • 10.
  • 11.
  • 12.
    // Print theelement names using getNodeName() from the Node interface. import org.w3c.dom.*; import javax.xml.parsers.*; public class SimpleWalker { protected DocumentBuilder docBuilder; protected Element root; public SimpleWalker() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); docBuilder = dbf.newDocumentBuilder(); DOMImplementation domImp = docBuilder.getDOMImplementation(); if (domImp.hasFeature(“XML”, “2.0”)) { System.out.println(“Parser supports extended interfaces”); } } Prepared By: Prabu.U
  • 13.
    public void parse(StringfileName) throws Exception { Document doc = docBuilder.parse(new FileInputStream(fileName)); root = doc.getDocumentElement(); System.out.println(“Root element is “ + root.getNodeName()); } public void printAllElements() throws Exception { printElement(“”, root); } Prepared By: Prabu.U
  • 14.
    public void printElement(Stringindent, Node aNode) { System.out.println(indent + “<” + aNode.getNodeName() + “>”); Node child = aNode.getFirstChild(); while (child != null) { printElement(indent + “t”, child); child = child.getNextSibling(); } System.out.println(indent + “</” + aNode.getNodeName() + “>”); } Prepared By: Prabu.U
  • 15.
    public static voidmain(String args[]) throws Exception { SimpleWalker sw = new SimpleWalker(); sw.parse(args[0]); sw.printAllElements(); } } // class SimpleWalker Prepared By: Prabu.U
  • 16.
    library.xml <?xml version=”1.0” encoding=”UTF-8”?> <library> <fiction> <book>MobyDick</book> <book>The Last Trail</book> </fiction> <biography> <book>The Last Lion, Winston Spencer Churchill</book> </biography> </library> Prepared By: Prabu.U
  • 17.
    Output from SimpleWalker <library><#text> </#text> <fiction> <#text></#text> <book> <#text> </#text> </book> <#text> </#text> <book> <#text> </#text> </book> <#text> </#text> </fiction> <#text> </#text> <biography> <#text> </#text> <book> <#text> </#text> </book> <#text> </#text> </biography> <#text> </#text> </library> Prepared By: Prabu.U
  • 18.
    If we callgetNodeName() on a text node, we get #text, not the text itself. If we want to get the text, we must determine whether we have a text node and then call getNodeValue(). Prepared By: Prabu.U
  • 19.
    public void printElement(Stringindent, Node aNode) { if (aNode.getNodeType() == Node.TEXT_NODE) { System.out.println(indent + aNode.getNodeValue()); } else { System.out.println(indent + “<” + aNode.getNodeName() + “>”); Node child = aNode.getFirstChild(); while (child != null) { printElement(indent + “t”, child); child = child.getNextSibling(); } System.out.println(indent + “</” + aNode.getNodeName() + “>”); } } Prepared By: Prabu.U
  • 20.
    Output After printElement()Modification <library> <fiction> <book> Moby Dick </book> <book> The Last Trail </book> </fiction> <biography> <book> The Last Lion, Winston Spencer Churchill </book> </biography> </library> Prepared By: Prabu.U
  • 21.
    DOM Traversal andRange  Traversal and range are features added in DOM Level 2.  They are supported by Apache Xerces.  You can determine whether traversal is supported by calling the hasFeature() method of the DOMImplementation interface.  For traversal, you can use the arguments “Traversal” and “2.0” for the feature and version parameters of the hasFeature() method. Prepared By: Prabu.U
  • 22.
    Traversal  Traversal isa convenient way to walk through a DOM tree and select specific nodes.  This is useful when you want to find certain elements and perform operations on them. Prepared By: Prabu.U
  • 23.
  • 24.
    Traversal <?xml version=”1.0” encoding=”UTF-8”?> <library> <fiction> <book>MobyDick</book> <book>The Last Trail</book> </fiction> <biography> <book>The Last Lion, Winston Spencer Churchill</book> </biography> </library> Prepared By: Prabu.U
  • 25.
    Traversal IteratorApp.java public void parse(StringfileName) throws Exception { document = docBuilder.parse(new FileInputStream(fileName)); root = document.getDocumentElement(); System.out.println(“Root element is “ + root.getNodeName()); } Prepared By: Prabu.U
  • 26.
    Traversal public void iterate() { NodeIteratoriter = ((DocumentTraversal)document).createNodeIterator( root, NodeFilter.SHOW_ELEMENT, new NameNodeFilter(“book”), true); Node n = iter.nextNode(); while (n != null) { System.out.println(n.getFirstChild().getNodeValue()); n = iter.nextNode(); } } Prepared By: Prabu.U
  • 27.
    Traversal OUTPUT: Root element islibrary Moby Dick The Last Trail The Last Lion, Winston Spencer Churchill Prepared By: Prabu.U
  • 28.
    Range  Range interfacesprovide a convenient way to select, delete, extract, and insert content.  You can determine whether range is supported by calling the hasFeature(...) method of the DOMImplementation interface.  You can use the arguments “Range” and “2.0” for feature and version.  There are a number of applications for which the range interfaces are useful. Prepared By: Prabu.U
  • 29.
  • 30.
    Other DOM Implementations For a variety of reasons, some have argued that DOM as specified by the W3C is not the best way to go.  One reason is that it’s too complex. In this case, JDOM has appeared as an alternative.  Another reason is that DOM takes too much memory and is not practical for resource-constrained devices such as PDAs and cellular phones. Prepared By: Prabu.U
  • 31.
    JDOM  JDOM isnot an acronym. It was originally developed as an open- source API for XML but has been accepted by the Java Community Process (JCP JSR-102).  The home of JDOM is www.jdom.org.  JDOM was designed specifically for Java. In contrast, DOM is purely an interface specification independent of any language.  For example, a Java parser can leverage standard Java types and collections, such as the String class and the Collections API. Prepared By: Prabu.U
  • 32.
    Here are someof the guiding principles of JDOM:  JDOM should be straightforward for Java programmers.  JDOM should support easy and efficient document modification.  JDOM should hide the complexities of XML wherever possible, while remaining true to the XML specification.  JDOM should integrate with DOM and SAX.  JDOM should be lightweight and fast.  JDOM should solve 80 percent (or more) of Java/XML problems with 20 percent (or less) of the effort when compare with DOM. Prepared By: Prabu.U
  • 33.
    Java Architecture forXML Binding (JAXB) Modeling Databases in XML  In the JAXB framework, we can parse XML documents into a suitable Java object. This technique is referred to as unmarshaling.  The JAXB framework also provides the capability to generate XML documents from Java objects, which is referred to as marshaling. Prepared By: Prabu.U
  • 34.
    JAXB (Java APIfor XML Binding) Solution The following steps are followed 1. Review the database schema. 2. Construct the desired XML document. 3. Define a schema for the XML document. 4. Create the JAXB binding schema. 5. Generate the JAXB classes based on the schema. 6. Develop a Data Access Object (DAO). 7. Develop a servlet for HTTP access.. Prepared By: Prabu.U
  • 35.
    Defining a Schemafor the XML Document rental_property.dtd Prepared By: Prabu.U
  • 36.
    Creating the JAXBBinding Schema rental_property.xjs (for XML Java schema) Prepared By: Prabu.U
  • 37.
    Generating the JAXBClasses Based on Schemas Prepared By: Prabu.U
  • 38.
    Generating the JAXBClasses Based on Schemas The following files are generated: RentalPropertyList.java: This file models the <rental_property_list> element. RentalProperty.java: This file models the <rental_property> element. Address.java: This file models the <address> subelement. Contact.java: This file models the <contact> subelement. Prepared By: Prabu.U
  • 39.
    Developing a DataAccess Object (DAO) A Data Access Object (DAO) provides access to the backend database. The goal of the DAO design pattern is to provide a higher level of abstraction for database access. Prepared By: Prabu.U
  • 40.
    Parsing XML UsingSimple API for XML (SAX) What Is SAX, Anyway? What SAX Is Not ? Why Do I Need SAX? SAX vs. DOM Disadvantages SAX Versions SAX Basics Working with SAX Prepared By: Prabu.U
  • 41.
    What Is SAX,Anyway?  SAX is an API that can be used to parse XML documents.  A parser is a program that reads data, a character at a time and returns manageable pieces of data.  For example, a parser for the English language might break up a document into paragraphs, words, and punctuation.  In the case of XML, the important pieces of data include elements, attributes, text, and so on. This is what SAX does. Prepared By: Prabu.U
  • 42.
    What Is SAX,Anyway?  SAX provides a framework for defining event listeners, or handlers. These handlers are written by developers interested in parsing documents with a known structure.  The handlers are registered with the SAX framework in order to receive events.  Events can include start of document, start of element, end of element, and so on.  The handlers contain a number of methods that will be called in response to these events.  Once the handlers are defined and registered, an input source can be specified and parsing can begin. Prepared By: Prabu.U
  • 43.
    What SAX IsNot ?  SAX by itself is just an API, and a number of implementations are available from many of the familiar sources.  The most commonly used parsers are Xerces from the Apache XML project and Java API for XML Processing (JAXP) from Sun Microsystems.  SAX was originally developed in Java, but similar implementations are available in other languages as well. There are implementations for Perl, Python, and C++, for example. Prepared By: Prabu.U
  • 44.
    Why Do INeed SAX?  If a tool or a standalone program is written to process XML, SAX is a good way to do it.  Many applications today can be customized using an XML file. These files have replaced the traditional “properties” files for reasons of uniformity and richness of expression.  Instead of spending a lot of time writing a parser to read XML files, SAX can be used.  SAX is completely free, so it can be embedded in a larger application without royalty fees or even copyright notices.  Some SAX parsers can validate a document against a Document Type Definition (DTD). Prepared By: Prabu.U
  • 45.
    SAX vs. DOM SAXis, in many ways, much simpler than DOM  There is no need to model every possible type of object that can be found in an XML document. This makes the API easy to understand and easier to use.  DOM contains many interfaces, each containing many methods. SAX is comprised of a handful of classes and interfaces.  SAX is a much lower-level API when compared with DOM. For these reasons, SAX parsers tend to be smaller than DOM implementations.  In fact, many DOM implementations use SAX parsers under the hood to read in XML documents. Prepared By: Prabu.U
  • 46.
    SAX vs. DOM SAXis an event-based API  Instead of loading an entire document into memory all at once, SAX parsers read documents and notify a client program when elements, text, comments, and other data of interest are found.  SAX parsers send you events continuously, telling you what was found next. Prepared By: Prabu.U
  • 47.
    SAX vs. DOM TheDOM parses XML in space, whereas SAX parses XML in time  In essence, the DOM parser hands you an entire document and allows you to traverse it any way you like. This can take a lot of memory, so SAX can be significantly more efficient for large documents.  In fact, you can process documents larger than available system memory, but this is not possible with DOM. SAX can also be faster, because you don’t have to wait for the entire document to be loaded. This is especially valuable when reading data over a network. Prepared By: Prabu.U
  • 48.
    Disadvantages  SAX isnot a perfect solution for all problems. For instance, it can be a bit harder to visualize compared to DOM because it is an event- driven model.  SAX parsing is “single pass,” so you can’t back up to an earlier part of the document any more than you can back up from a serial data stream.  Moreover, you have no random access at all. Handling parent/child relationships can be more challenging as well. Prepared By: Prabu.U
  • 49.
    Disadvantages  Another disadvantageis that the current SAX implementations are read-only parsers.  They do not provide the ability to manipulate a document or its structure (this feature may be added in the future).  DOM is the way to go if you want to manipulate a document in memory. Prepared By: Prabu.U
  • 50.
    SAX Versions  Thefirst version, SAX 1.0, was released in May 1998.  It provided the basic functionality needed to read elements, attributes, text, and to manage errors.  There was also some DTD support. Prepared By: Prabu.U
  • 51.
    SAX Versions  Thecurrent version, SAX 2.0, was released two years later in May 2000.  Many of the SAX 2.0 interfaces are departures from SAX 1.0. Older interfaces are included, but deprecated, for backward compatibility.  Adapters are included for using SAX 1.0 parsers with SAX 2.0, and vice versa.  SAX 2.0 also includes support for namespaces and extensibility through features and properties. Documentation is improved as well. Prepared By: Prabu.U
  • 52.
    SAX Basics <?xml version=”1.0”encoding=”UTF-8”?> <fiction> <book author=”Herman Melville”>Moby Dick</book> </fiction> Prepared By: Prabu.U
  • 53.
    SAX Basics  Ifyou want to parse this document using SAX, you would build a content handler by creating a Java class that implements the ContentHandler interface in the org.xml.sax package.  Once you have a content handler, you simply register it with a SAX XMLReader, set up the input source, and start the parser.  Next, the methods in your content handler will be called when the parser encounters elements, text, and other data. Prepared By: Prabu.U
  • 54.
    SAX Basics  Specifically,the events generated will look something like this: start document start element: fiction start element: book (including attributes) characters: Moby Dick end element: book end element: fiction end document Prepared By: Prabu.U
  • 55.
    SAX Packages  TheSAX 2.0 API is comprised of two standard packages and one extension package.  The standard packages are org.xml.sax and org.xml.helpers.  The org.xml.sax package contains the basic classes, interfaces, and exceptions needed for parsing documents Prepared By: Prabu.U
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
    Working with SAX importjava.io.*; import org.xml.sax.*; import org.xml.sax.helpers.*; import javax.xml.parsers.*; public class SAXDemo extends DefaultHandler { public void startDocument() { System.out.println(“***Start of Document***”); } public void endDocument() { System.out.println(“***End of Document***”); } public void startElement(String uri, String localName, String qName, Attributes attributes) { public void startElement(String uri, String localName, String qName, Attributes attributes) { System.out.print(“<” + qName); int n = attributes.getLength(); for (int i=0; i<n; i+=1) { System.out.print(“ “ + attributes.getQName(i) + “=’” + attributes.getValue(i) + “‘“); } System.out.println(“>”); } public void characters(char[] ch, int start, int length) { System.out.println(new String(ch, start, length).trim()); } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { System.out.println(“</” + qName + “>”); } Prepared By: Prabu.U
  • 63.
    Working with SAX publicstatic void main(String args[]) throws Exception { if (args.length != 1) { System.err.println(“Usage: java SAXDemo <xml- file>”); System.exit(1); } SAXDemo handler = new SAXDemo(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(new File(args[0]), handler); } } Prepared By: Prabu.U
  • 64.
  • 65.
  • 66.
    library.xml <?xml version=”1.0” encoding=”UTF-8”?> <!DOCTYPElibrary SYSTEM “library.dtd”> <library> <fiction> <book author=”Herman Melville”>Moby Dick</book> <book author=”Zane Grey”>The Last Trail</book> </fiction> <biography> <book author=”William Manchester”> The Last Lion, Winston Spencer Churchill </book> </biography> <science> <book author=”Hecht, Zajac”>Optics</book> </science> </library> Prepared By: Prabu.U
  • 67.
    Output from SAXDemo ***Startof Document*** <library> <fiction> <book author=’Herman Melville’> Moby Dick </book> <book author=’Zane Grey’> The Last Trail </book> </fiction> <biography> <book author=’William Manchester’> The Last Lion, Winston Spencer Churchill </book> </biography> <science> <book author=’Hecht, Zajac’> Optics </book> </science> </library> ***End of Document*** Prepared By: Prabu.U
  • 68.
  • 69.
  • 70.
    XML Transformation andXSL  XSL Technologies  XSLT for Document Publishing  XSL for Business-to-Business (B2B) Communication  XSL Formatting Objects  Web Application Integration: Java Servlets, XSLT, and XSL-FO Prepared By: Prabu.U
  • 71.
    XSL Technologies  XSLhas two independent languages:  The XSL Transformation Language (XSLT)  The XSL Formatting Object Language (XSL-FO)  XSLT is used to convert an XML document to another format.  XSL-FO provides a way of describing the presentation of an XML document.  Both technologies use a supporting XML technology, XPath. Prepared By: Prabu.U
  • 72.
    XSLT for DocumentPublishing  XSL technology has an important role in the field of document publishing.  Imagine, for example, that we have an XML document for a list of books.  We would like to publish this document in various formats.  Using XSL, we can convert the book list to an HTML file, PDF document, or other format.  The key to this example is the XML document, which serves as a single data source Prepared By: Prabu.U
  • 73.
    XSLT for DocumentPublishing  By applying an XSL style sheet, we render a new view of the data.  The development of multiple style sheets allows us to have multiple views of the same data.  This approach provides a clean separation of the data (the XML document) and the view (the XSL style sheet).  We can also extend this example to support wireless Internet clients.  A growing number of mobile phones and PDAs support the Wireless Application Protocol (WAP). Prepared By: Prabu.U
  • 74.
    XSLT for DocumentPublishing  These WAP enabled devices contain a mini browser for rendering Wireless Markup Language (WML) documents.  To support the wireless Internet clients, all we have to do is design an appropriate XSL style sheet to convert the XML document to WML.  No modifications are required to the original XML document. Prepared By: Prabu.U
  • 75.
    Publishing documents withXSLT Prepared By: Prabu.U
  • 76.
    Sending data tothe XSLT processor  XSLT provides the mechanism for converting an XML document to another format.  This is accomplished by applying an XSLT style sheet to the XML document.  The style sheet contains conversion rules for accessing and transforming the input XML document to a different output format.  An XSLT processor is responsible for applying the rules defined in the style sheet to the input XML document. Prepared By: Prabu.U
  • 77.
    Sending data tothe XSLT processor Prepared By: Prabu.U
  • 78.
    Creating the XSLStyle Sheet book_view.xsl <?xml version=”1.0”?> <xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0”> <xsl:template match=”/book”> <html><body> <b>Title: </b> <xsl:value-of select=”title” /> <p/> <b>By: </b> <xsl:value-of select=”author” /> <p/> <b>Cost: </b> <xsl:value-of select=”price” /> <p/> <b>Category: </b> <xsl:value-of select=”category” /> <p/> <b>Description</b> <p/> <i><xsl:value-of select=”summary” /></i> </body></html> </xsl:template> </xsl:stylesheet> Prepared By: Prabu.U
  • 79.
    Creating the XMLDocument <?xml version=”1.0”?> <book> <author>Michael Daconta et al</author> <title>XML Development with Java 2</title> <category>Java</category> <price currency=”USD”>44.99</price> <summary> XML Development with Java 2 provides the information and techniques a Java developer will need to integrate XML into Java- based applications. </summary> </book> Prepared By: Prabu.U
  • 80.
    Getting Started withXSLT Prepared By: Prabu.U
  • 81.
    The Missing Piece:The XSLT Processor Prepared By: Prabu.U
  • 82.
     Two techniquesare available for performing the XSLT processing: client-side processing and server-side processing.  Client-side XSLT processing commonly occurs in a Web browser. The Web browser includes an XSLT processor and retrieves the XML document and XSL style sheet.  The client-side technique offloads the XSLT processing to the client machine.  This minimizes the workload on the Web server. However, the disadvantage is that the Web browser must provide XSLT support. Prepared By: Prabu.U
  • 83.
     At thetime of this writing, Netscape Communicator 6 and Microsoft Internet Explorer 6 support the XSLT 1.0 specification.  Microsoft Internet Explorer 5.x has very limited support for XSLT 1.0. The previous version of the Netscape browser, 4.x, provides no support for XSLT.  The client-side technique is applicable when you’re deploying an application in a controlled environment.  For example, in a corporate environment, the system administrators can install the latest version of the Web browser that conforms to the XSLT 1.0 specification. Prepared By: Prabu.U
  • 84.
  • 85.
     Server-side XSLTprocessing occurs on the Web server or application server.  A serverside process such as an Active Server Page (ASP), JavaServer Page (JSP), or Java servlet will retrieve the XML document and XSL style sheet and pass them to an XSLT processor.  The output of the XSLT processor is sent to the client Web browser for presentation.  The output is generally a markup language, such as HTML, that is understood by the client browser. Prepared By: Prabu.U
  • 86.
  • 87.
    Implementing Client-Side XSLTProcessing book.xml <?xml version=”1.0”?> <?xml-stylesheet type=”text/xsl” href=”book_view.xsl”?> <book> <author>Michael Daconta et al</author> <title>XML Development with Java 2</title> <category>Java</category> <price currency=”USD”>44.99</price> <summary> XML Development with Java 2 provides the information and techniques a Java developer will need to integrate XML into Java-based applications. </summary> </book> Prepared By: Prabu.U
  • 88.
    book_view.xsl <?xml version=”1.0”?> <xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”version=”1.0”> <xsl:template match=”/book”> <html><body> <b>Title: </b> <xsl:value-of select=”title” /> <p/> <b>By: </b> <xsl:value-of select=”author” /> <p/> <b>Cost: </b> <xsl:value-of select=”price” /> <p/> <b>Category: </b> <xsl:value-of select=”category” /> <p/> <b>Description</b> <p/> <i><xsl:value-of select=”summary” /></i> </body></html> </xsl:template> </xsl:stylesheet> Prepared By: Prabu.U
  • 89.
    XSLT rendered ina Web browser Prepared By: Prabu.U
  • 90.
    Implementing Server-Side XSLTProcessing  A number of server-side technologies are available, including Common Gateway Interface (CGI), ColdFusion, Hypertext Processor (PHP), and so on.  Here focuses on server-side processing with Microsoft’s Active Server Pages (ASP) and Sun Microsystem’s JavaServer Pages (JSP). Prepared By: Prabu.U
  • 91.
    ASP: Server-Side XSLTProcessing  In order to develop using ASP, you will need the IIS Web server and the latest version of the Microsoft XML parser. The required components are listed below.  Microsoft IIS Web Server 5.0. This version of IIS is included with Microsoft Windows 2000 Professional. You can also use IIS 4.0 or Personal Web Server (PWS); however, you will have to install the Windows NT Option Pack 4. Refer to Microsoft’s Web site for details on adding ASP support to IIS 4.0 and PWS.  Microsoft XML Parser 3.0. If you have IE 6 installed on your server machine, then MS XML Parser 3.0 is included. The MS XML Parser 3.0 is also available as a separate download from http://msdn.microsoft.com. Prepared By: Prabu.U
  • 92.
    book_test.asp <%@ Language=VBScript %> <% setxml = Server.CreateObject(“Microsoft.XMLDOM”) xml.load(Server.MapPath(“book.xml”)) set xsl = Server.CreateObject(“Microsoft.XMLDOM”) xsl.load(Server.MapPath(“book_view.xsl”)) Response.Write(xml.transformNode(xsl)) %> Prepared By: Prabu.U
  • 93.
  • 94.
    JSP: Server-Side XSLTProcessing  Sun Microsystems provides a server-side technology that is very similar to ASP.  Of course, the server-side scripting is accomplished in Java. In order to perform the serverside processing with JSP, you will need to install the Java Software Development Kit (SDK) along with a compliant JSP server container. Here’s a list of required components: Prepared By: Prabu.U
  • 95.
    JSP: Server-Side XSLTProcessing  Sun Microsystems’ Software Development Kit (SDK) 1.3 (or higher). The SDK is available at Sun’s Web site, http://java.sun.com/j2se. Follow the installation instructions provided with the SDK.  Apache Tomcat Server 4. Apache Tomcat 4 is the official reference implementation for JSP 1.2 and Java Servlets 2.3. If your application server already supports JSP 1.1 or higher, there is no requirement to install Tomcat. Apache Tomcat 4 is available from the Apache Web site, http://jakarta.apache.org/tomcat. Prepared By: Prabu.U
  • 96.
    book_test.jsp <%@ taglib uri=”http://jakarta.apache.org/taglibs/xsl-1.0” prefix=”jakarta”%> <jakarta:apply xml=”book.xml” xsl=”book_view.xsl” /> Prepared By: Prabu.U
  • 97.
    XSL for Business-to-Business(B2B) Communication  The process of exchanging data between two different companies.  Developers can leverage XML to describe the data in a vendor- independent fashion.  In the ideal case, both companies will agree upon a standard vocabulary for describing the data using a DTD or schema.  The vocabulary is composed of the XML element names used in the XML document.  However, in certain cases one of the companies might like to use a different vocabulary. This is where XSL enters the picture. Prepared By: Prabu.U
  • 98.
  • 99.
    XSL for Business-to-Business(B2B) Communication  The example describes a B2B scenario between a training company, Hot Shot Training, and a software development company, AcmeSoft.  The computer training company maintains a database for the students that have attended its courses.  The training company has developed an XML application that produces the list of students for a given class. Prepared By: Prabu.U
  • 100.
     The XMLapplication at the training company is accessible using the HTTP protocol.  The first step is to request the XML document from the training company.  In step 2, the XML document is retrieved.  In step 3, the document is transformed using the supplied XSLT style sheet.  Finally, the desired output document is produced in step 4. Prepared By: Prabu.U
  • 101.
    <?xml version=”1.0”?> <trainingclass> <title>J2EE Essentials</title> <start_date>24Sep 2001</start_date> <end_date>28 Sep 2001</end_date> <location>Philadelphia, PA</location> <student> <first_name>Riley</first_name> <last_name>Scott</last_name> <email>riley@acmesoft.web</email> </student> <student> <first_name>Torrance</first_name> <last_name>Lee</last_name> <email>torrance.lee@acmesoft.web</email> </student> </trainingclass> Prepared By: Prabu.U
  • 102.
    <?xml version=”1.0”?> <employeelist> <course_title>J2EE Essentials</course_title> <course_datestart=”24 Sep 2001” end=”28 Sep 2001” /> <location>Philadelphia, PA</location> <employee> <name> <first>Riley</first> <last>Scott</last> </name> <email>riley.scott@acmesoft.web</email> </employee> <employee> <name> <first>Torrance</first> <last>Lee</last> </name> <email>torrance.lee@acmesoft.web</email> </employee> </employeelist> Prepared By: Prabu.U
  • 103.
    Creating the XSLStyle Sheet  The XSL style sheet will contain the template for the <employeelist> document, and the XSL elements will be leveraged to retrieve the data from the <trainingclass> document.  The transformation is fairly straightforward, except for one area. The training company describes the date for the class using the elements <start_date> and <end_date>, as shown here: <start_date>24 Sep 2001</start_date> <end_date>28 Sep 2001</end_date> Prepared By: Prabu.U
  • 104.
    Creating the XSLStyle Sheet  AcmeSoft stores the date as a single element with two attributes for the start and end: <course_date start=”24 Sep 2001” end=”28 Sep 2001” /> Prepared By: Prabu.U
  • 105.
    Creating the XSLStyle Sheet  In this case, <xsl:attribute> can be used to create attributes for <course_date>: <course_date> <xsl:attribute name=”start”> <xsl:value-of select=”start_date”/> </xsl:attribute> <xsl:attribute name=”end”> <xsl:value-of select=”end_date”/> </xsl:attribute> </course_date> Prepared By: Prabu.U
  • 106.
    train2employee.xsl <?xml version=”1.0”?> <xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0”> <xsl:templatematch=”/trainingclass”> <employeelist> <course_title><xsl:value-of select=”title” /></course_title> <course_date> <xsl:attribute name=”start”> <xsl:value-of select=”start_date”/> </xsl:attribute> <xsl:attribute name=”end”> <xsl:value-of select=”end_date”/> </xsl:attribute> </course_date> <location><xsl:value-of select=”location” /></location> Prepared By: Prabu.U
  • 107.
    <!-- Perform aloop for each student in the training class --> <xsl:for-each select=”student” <employee> <name> <first><xsl:value-of select=”first_name”/></first> <last><xsl:value-of select=”last_name”/></last> </name> <email><xsl:value-of select=”email”/></email> </employee> </xsl:for-each> </employeelist> </xsl:template> </xsl:stylesheet> Prepared By: Prabu.U
  • 108.
    XSL Formatting Objects XSL-FOFormatting Engines Prepared By: Prabu.U
  • 109.
    Basic Document Structure The following code snippet shows the basic document setup for XSL-FO: <?xml version=”1.0” encoding=”utf-8”?> <fo:root xmlns:fo=”http://www.w3.org/1999/XSL/Format”> <!-- layout master set --> <!-- page masters: size and layout --> <!-- page sequences and content --> </fo:root> Prepared By: Prabu.U
  • 110.
    Basic Document Structure The element <fo:root> is the root element for the XSL-FO document. An XSL-FO document can contain the following components: • Page master • Page master set • Page sequences Prepared By: Prabu.U
  • 111.
    Page Master: <fo:page-master> The <fo:simple-page-master> element defines the layout of a page. The following code snippet describes a U.S. letter: <fo:simple-page-master master-name=”simple” page-height=”11in” page-width=”8.5in” margin-top=”1in” margin-bottom=”1in” margin-left=”1.25in” margin-right=”1.25in”> </fo:simple-page-master> Prepared By: Prabu.U
  • 112.
    Components of thepage master Prepared By: Prabu.U
  • 113.
    Five regions ofa page Prepared By: Prabu.U
  • 114.
    Five regions ofa page The following example defines the dimensions for <fo:region- body>, <fo:regionbefore>, and <fo:region-after>: <fo:simple-page-master master-name=”simple” page-height=”11in” page-width=”8.5in”> <fo:region-body margin-top=”0.5in”/> <fo:region-before extent=”0.5in”/> <fo:region-after extent=”0.5in”/> </fo:simple-page-master> Prepared By: Prabu.U
  • 115.
    Page Master Set:<fo:page-master-set> <fo:layout-master-set> <fo:simple-page-master master-name=”simple” page-height=”11in” page-width=”8.5in” margin-top=”1in” margin-bottom=”1in” margin-left=”1.25in” margin-right=”1.25in”> <fo:region-body margin-top=”0.5in”/> <fo:region-before extent=”3cm”/> <fo:region-after extent=”1.5cm”/> </fo:simple-page-master> </fo:layout-master-set> Prepared By: Prabu.U
  • 116.
    Page Master Set:<fo:page-master-set>  A document can be composed of multiple pages, each with its own dimensions. The page master set refers to the collection of page masters.  In the following code example, a page master set is defined that contains one page set: Prepared By: Prabu.U
  • 117.
  • 118.
    Page Sequences: <fo:page-sequence> A page sequence defines a series of printed pages. Each page sequence refers to a page master for its dimensions.  The page sequence contains the actual content for the document.  The <fo:page-sequence> element contains <fo:static-content> and <fo:flow> elements. Prepared By: Prabu.U
  • 119.
    Page Sequences: <fo:page-sequence> The <fo:static-content> element is used for page headers and footers.  For example, we can define a header for the company name and page number, and this information will appear on every page.  The <fo:flow> element contains a collection of text blocks. The <fo:flow> element is similar to a collection of paragraphs. Prepared By: Prabu.U
  • 120.
    Page Sequences: <fo:page-sequence> A body of text is defined using the <fo:block> element.  The <fo:block> element is a child element of <fo:flow>. The <fo:block> element contains free-flowing text that will wrap to the next line in a document if it overflows. Prepared By: Prabu.U
  • 121.
    simple.fo <!-- page sequencesand content --> <fo:page-sequence master-name=”simple”> <fo:flow flow-name=”xsl-region-body”> <!-- this defines a level 1 heading with orange background --> <fo:block font-size=”18pt” font-family=”sans-serif” line-height=”24pt” space-after.optimum=”15pt” background-color=”orange” color=”white” text-align=”center” padding-top=”3pt”> Ez Books Online </fo:block> Prepared By: Prabu.U
  • 122.
    <!-- Paragraph thatcontains info about the company --> <fo:block font-size=”12pt” font-family=”sans-serif” line-height=”15pt” space-after.optimum=”14pt” text-align=”justify”> Welcome to Ez Books Online, the world’s smallest online book store. Our company’s mission is to sell books on Java, Thrillers and Romance. We have something for everyone...so we think. Feel free to browse our catalog and if you find a book of interest then send us an e-mail. Thanks for visiting! </fo:block> </fo:flow> </fo:page-sequence> Prepared By: Prabu.U
  • 123.
    Page Headers andFooters header_footer.fo <fo:page-sequence master-name=”simple”> <!-- header --> <fo:static-content flow-name=”xsl-region-before”> <fo:block text-align=”end” font-size=”10pt” font-family=”serif” line-height=”14pt” > Ez Books Catalog - page <fo:page-number/> </fo:block> </fo:static-content> Prepared By: Prabu.U
  • 124.
    <!-- footer --> <fo:static-contentflow-name=”xsl-region-after”> <fo:block text-align=”center” font-size=”10pt” font-family=”serif” line-height=”14pt” > Visit our website http://www.ezbooks.web </fo:block> </fo:static-content> Prepared By: Prabu.U
  • 125.
    <!-- body --> <fo:flowflow-name=”xsl-region-body”> <!-- this defines a level 1 heading with orange background --> <fo:block font-size=”18pt” font-family=”sans-serif” line-height=”24pt” space-after.optimum=”15pt” background-color=”orange” color=”white” text-align=”center” padding-top=”3pt”> Ez Books Online </fo:block> Prepared By: Prabu.U
  • 126.
    <!-- insert pagebreak for second page --> <fo:block break-before=”page”> A page break is inserted before this block. Notice we have the headers and footers in place. This was accomplished with the fo-static-content elements. We can continue on...business as usual. </fo:block> Prepared By: Prabu.U
  • 127.
    <!-- insert pagebreak for third page --> <fo:block break-before=”page”> Information on our third page. Again...notice the page number is incrementing for us...automagically. Wouldn’t it be great to generate this XSL-FO page dynamically? Hold tight, dynamic demos are coming up! </fo:block> Prepared By: Prabu.U
  • 128.
    Graphics  XSL-FO alsoallows for the insertion of external graphic images. The graphic formats supported are dependent on the XSL-FO formatting engine.  The Apache-FOP formatting engine supports the popular graphics formats: GIF, JPEG, and BMP. Prepared By: Prabu.U
  • 129.
    Graphics The following codefragment inserts the image smiley.jpg: <fo:block text-align=”center”> <fo:external-graphic src=”smiley.jpg” width=”200px” height=”200px”/> </fo:block> Prepared By: Prabu.U
  • 130.
    Tables  XSL-FO hasrich support for structuring tabular data.  In fact, there are many similarities between HTML tables and XSL-FO tables. Prepared By: Prabu.U
  • 131.
    Comparing HTML TableElements and XSL-FO Table Elements Prepared By: Prabu.U
  • 132.
    <!-- table start--> <fo:table> <!-- define column widths --> <fo:table-column column-width=”120pt”/> <fo:table-column column-width=”200pt”/> <fo:table-column column-width=”80pt”/> Prepared By: Prabu.U
  • 133.
  • 134.
    <fo:table-body> <fo:table-row> <fo:table-cell> <fo:block>Michael Daconta</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>XML Developmentwith Java 2</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>37.99</fo:block> </fo:table-cell> </fo:table-row> Prepared By: Prabu.U
  • 135.
    <fo:table-row> <fo:table-cell> <fo:block>E. Lynn Harris</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>AnyWay The Wind Blows</fo:block> </fo:table-cell> <fo:table-cell> <fo:block>19.95</fo:block> </fo:table-cell> </fo:table-row> Prepared By: Prabu.U
  • 136.
  • 137.
  • 138.
    Modeling Databases inXML Prepared By: Prabu.U
  • 139.
    1. Review thedatabase schema. 2. Construct the desired XML document. 3. Define a schema for the XML document. 4. Create the JAXB binding schema. 5. Generate the JAXB classes based on the schema. 6. Develop a Data Access Object (DAO). 7. Develop a servlet for HTTP access. JAXB Solution Prepared By: Prabu.U
  • 140.
    Reviewing the DatabaseSchema Prepared By: Prabu.U
  • 141.
    Reviewing the DatabaseSchema Prepared By: Prabu.U
  • 142.
    Constructing the DesiredXML Document Prepared By: Prabu.U
  • 143.
    Constructing the DesiredXML Document Prepared By: Prabu.U
  • 144.
    rental_property.dtd <!ELEMENT rental_property_list (rental_property)*> <!ELEMENT rental_property (prop_id, name, address, square_footage, bedrooms, bath, price, contact)> <!ELEMENT prop_id (#PCDATA)> <!ELEMENT name (#PCDATA)> <!ELEMENT address (street, city, state, postal_code)> <!ELEMENT street (#PCDATA)> <!ELEMENT city (#PCDATA)> <!ELEMENT state (#PCDATA)> <!ELEMENT postal_code (#PCDATA)> Defining a Schema for the XML Document Prepared By: Prabu.U
  • 145.
    <!ELEMENT square_footage (#PCDATA)> <!ELEMENTbedrooms (#PCDATA)> <!ELEMENT bath (#PCDATA)> <!ELEMENT price (#PCDATA)> <!ELEMENT contact (phone, fax)> <!ELEMENT phone (#PCDATA)> <!ELEMENT fax (#PCDATA)> Defining a Schema for the XML Document Prepared By: Prabu.U
  • 146.
    rental_property.xjs <!DOCTYPE xml-java-binding-schema SYSTEM”http://java.sun.com/dtd/jaxb/1.0- ea/xjs.dtd”> <xml-java-binding-schema version=”1.0-ea”> <options package=”xmlunleashed.ch10.jaxb”/> <element name=”rental_property_list” type=”class” root=”true”> <content property=”list”/> </element> <element name=”square_footage” type=”value” convert=”double”/> <element name=”bedrooms” type=”value” convert=”double”/> <element name=”bath” type=”value” convert=”double”/> <element name=”price” type=”value” convert=”BigDecimal”/> <conversion name=”BigDecimal” type=”java.math.BigDecimal”/> </xml-java-binding-schema> Creating the JAXB Binding Schema Prepared By: Prabu.U
  • 147.
    Generating the JAXBClasses Based on Schemas Prepared By: Prabu.U
  • 148.
    Developing a DataAccess Object (DAO) Prepared By: Prabu.U
  • 149.
  • 150.
     A testharness is a small program that tests the basic functionality of the application.  If designed properly, The test harness provides a way of producing predictable results from an application. Creating a Test Harness for RentalPropertyDAO Prepared By: Prabu.U
  • 151.
     The TestAppprogram will construct the RentalPropertyDAO Data Access Object and then retrieve a list of RentalProperty objects by calling the method getRentalPropertyList().  The XML data is displayed by calling the marshal() method on RentalPropertyList. Creating a Test Harness for RentalPropertyDAO Prepared By: Prabu.U
  • 152.
    public class TestApp { protectedRentalPropertyDAO myRentalDAO; public TestApp() throws DAOException { myRentalDAO = new RentalPropertyDAO(); } public void process() throws DAOException, IOException { // Get the list of rental properties RentalPropertyList theList = myRentalDAO.getRentalProperties(); // Send the XML data to standard out. theList.marshal(System.out); } Prepared By: Prabu.U
  • 153.
    public static voidmain(String[] args) { try { TestApp myApp = new TestApp(); myApp.process(); } catch (Exception exc) { exc.printStackTrace(); } } Prepared By: Prabu.U
  • 154.
    Converting the XMLData to HTML with XSLT Prepared By: Prabu.U
  • 155.
    rental_view.xsl <?xml version=”1.0”?> <xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”version=”1.0”> <xsl:template match=”/rental_property_list”> <html><body> <h3>Rental Properties</h3> <hr></hr> <table border=”1” cellpadding=”5”> <tr> <th>Name</th> <th>Street</th> <th>City, State</th> <th>Square Footage</th> <th>Bedrooms</th> <th>Bath</th> <th>Price</th> </tr> Prepared By: Prabu.U
  • 156.
    <!— Perform loopfor each rental property in the list —> <xsl:for-each select=”rental_property” > <tr> <td> <xsl:value-of select=”name” /> </td> <td> <xsl:value-of select=”address/street” /> </td> <td> <xsl:value-of select=”address/city” />,<xsl:value-of select=”address/state” /> </td> <td> <xsl:value-of select=”square_footage” /> </td> <td> <xsl:value-of select=”bedrooms” /> </td> <td> <xsl:value-of select=”bath” /> </td> <td> $ <xsl:value-of select=”price” /> </td> </tr> </xsl:for-each> </table> </body></html> </xsl:template> </xsl:stylesheet> Prepared By: Prabu.U