SlideShare a Scribd company logo
1 of 156
BUILDING XML- BASED
APPLICATIONS
Parsing XML – using DOM, SAX
Prepared By: Prabu.U
– XML
Transformation and XSL – XSL Formatting –
Modeling Databases in XML
Parsing XML Using Document Object Model
Prepared By: Prabu.U
 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)
What Is DOM, Anyway?
Prepared By: Prabu.U
 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++.
What DOM Is Not ?
Prepared By: Prabu.U
 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.
Why Do I Need DOM?
Prepared By: Prabu.U
 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.
Why Do I Need DOM?
Prepared By: Prabu.U
 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.
Disadvantages of Using DOM
Prepared By: Prabu.U
 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.
DOM Core
Prepared By: Prabu.U
<purchase-order>
<customer>James Bond</customer>
<merchant>Spies R Us</merchant>
<items>
<item>Night vision camera</item>
<item>Vibrating massager</item>
</items>
</purchase-order>
DOM Core
Prepared By: Prabu.U
DOM Interface Relationships
Prepared By: Prabu.U
Extended Interfaces
Prepared By: Prabu.U
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>
DOM Traversal and Range
Prepared By: Prabu.U
 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.
Traversal
Prepared By: Prabu.U
 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.
Traversal Interfaces
Prepared By: Prabu.U
Traversal
Prepared By: Prabu.U
<?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>
Traversal
Prepared By: Prabu.U
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());
}
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
Prepared By: Prabu.U
OUTPUT:
Root element is library
Moby Dick
The Last Trail
The Last Lion, Winston Spencer Churchill
Range
Prepared By: Prabu.U
 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.
Range Interfaces
Prepared By: Prabu.U
Other DOM Implementations
Prepared By: Prabu.U
 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.
JDOM
Prepared By: Prabu.U
 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.
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
Prepared By: Prabu.U
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.
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?
Prepared By: Prabu.U
 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.
What Is SAX, Anyway?
Prepared By: Prabu.U
 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.
What SAX Is Not ?
Prepared By: Prabu.U
 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.
Why Do I Need SAX?
Prepared By: Prabu.U
 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).
SAX vs. DOM
Prepared By: Prabu.U
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.
SAX vs. DOM
Prepared By: Prabu.U
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.
SAX vs. DOM
Prepared By: Prabu.U
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.
Disadvantages
Prepared By: Prabu.U
 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.
Disadvantages
Prepared By: Prabu.U
 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.
SAX Versions
Prepared By: Prabu.U
 The first version, SAX 1.0, was released in May 1998.
 It provided the basic functionality needed to
attributes, text, and to manage errors.
read elements,
 There was also some DTD support.
SAX Versions
Prepared By: Prabu.U
 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.
SAX Basics
Prepared By: Prabu.U
<?xml version=”1.0” encoding=”UTF-8”?>
<fiction>
<book author=”Herman Melville”>Moby Dick</book>
</fiction>
SAX Basics
Prepared By: Prabu.U
 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.
SAX Basics
Prepared By: Prabu.U
 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
SAX Packages
Prepared By: Prabu.U
 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
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
Prepared By: Prabu.U
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 + “>”);
}
Working with SAX
Prepared By: Prabu.U
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);
}
}
The ContentHandler Methods
Prepared By: Prabu.U
The ContentHandler Methods
Prepared By: Prabu.U
library.xml
Prepared By: Prabu.U
<?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>
Output from SAXDemo
Prepared By: Prabu.U
***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***
The ErrorHandler Methods
Prepared By: Prabu.U
The LexicalHandler Methods
Prepared By: Prabu.U
XML Transformation and XSL
Prepared By: Prabu.U
 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
XSL Technologies
Prepared By: Prabu.U
 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.
XSLT for Document Publishing
Prepared By: Prabu.U
 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
XSLT for Document Publishing
Prepared By: Prabu.U
 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.
 Agrowing number of mobile phones and PDAs support the Wireless
Application Protocol (WAP).
XSLT for Document Publishing
Prepared By: Prabu.U
 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.
Publishing documents with XSLT
Prepared By: Prabu.U
Sending data to the XSLT processor
Prepared By: Prabu.U
 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.
Sending data to the XSLT processor
Prepared By: Prabu.U
Creating the XSL Style Sheet
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>
Creating the XML Document
Prepared By: Prabu.U
<?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>
Getting Started with XSLT
Prepared By: Prabu.U
The Missing Piece: The XSLT Processor
Prepared By: Prabu.U
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
Implementing Client-Side XSLT Processing
Prepared By: Prabu.U
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>
XSLT rendered in a Web browser
Prepared By: Prabu.U
Implementing Server-Side XSLT Processing
Prepared By: Prabu.U
 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).
ASP: Server-Side XSLT Processing
Prepared By: Prabu.U
 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
JSP: Server-Side XSLT Processing
Prepared By: Prabu.U
 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:
JSP: Server-Side XSLT Processing
Prepared By: Prabu.U
 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” />
XSL for Business-to-Business (B2B)
Communication
Prepared By: Prabu.U
 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
XSL for Business-to-Business (B2B)
Communication
Prepared By: Prabu.U
 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>
Creating the XSL Style Sheet
Prepared By: Prabu.U
 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>
Creating the XSL Style Sheet
Prepared By: Prabu.U
 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” />
Creating the XSL Style Sheet
Prepared By: Prabu.U
 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>
XSL Formatting Objects
XSL-FO Formatting Engines
Prepared By: Prabu.U
Basic Document Structure
Prepared By: Prabu.U
 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>
Basic Document Structure
Prepared By: Prabu.U
 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
Page Master: <fo:page-master>
Prepared By: Prabu.U
 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>
Components of the page master
Prepared By: Prabu.U
Five regions of a page
Prepared By: Prabu.U
Five regions of a page
Prepared By: Prabu.U
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>
Page Master Set: <fo:page-master-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>
Page Master Set: <fo:page-master-set>
Prepared By: Prabu.U
 Adocument 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>
Page Sequences: <fo:page-sequence>
Prepared By: Prabu.U
 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.
Page Sequences: <fo:page-sequence>
Prepared By: Prabu.U
 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.
Page Sequences: <fo:page-sequence>
Prepared By: Prabu.U
 Abody 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>
Page Headers and Footers
Prepared By: Prabu.U
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>
Graphics
Prepared By: Prabu.U
 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.
Graphics
Prepared By: Prabu.U
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>
Tables
Prepared By: Prabu.U
 XSL-FO has rich support for structuring tabular data.
 In fact, there are many similarities between HTML tables
and XSL-FO tables.
Comparing HTML Table Elements and XSL-FO Table Elements
Prepared By: Prabu.U
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>
<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
r
Pe
p
a
ar
e
d
cB
cy
e:P
sr
a
sb
u
..
U
JAXB Solution
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,
square_footage, bedrooms, bath, price, contact)>
address,
<!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 (#P
Pr
e
Cp
a
r
De
dB
Ay
:TP
r
a
Ab
u
.
)U
>
Defining a Schema for the XML Document
<!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
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();
}
}
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
</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
select=”address/state” />

More Related Content

Similar to buildingxmlbasedapplications-180322042009.pptx

Xml and xml processor
Xml and xml processorXml and xml processor
Xml and xml processorHimanshu Soni
 
0001 Genero Terms
0001 Genero Terms0001 Genero Terms
0001 Genero Termsguest174e18
 
0001 Genero Terms
0001 Genero Terms0001 Genero Terms
0001 Genero Termsguest174e18
 
Validating Xml
Validating XmlValidating Xml
Validating XmlLiquidHub
 
Working with xml data
Working with xml dataWorking with xml data
Working with xml dataaspnet123
 
04 sm3 xml_xp_07
04 sm3 xml_xp_0704 sm3 xml_xp_07
04 sm3 xml_xp_07Niit Care
 
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...Marco Gralike
 
epicenter2010 Open Xml
epicenter2010   Open Xmlepicenter2010   Open Xml
epicenter2010 Open XmlCraig Murphy
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)BOSS Webtech
 
Code Documentation. That ugly thing...
Code Documentation. That ugly thing...Code Documentation. That ugly thing...
Code Documentation. That ugly thing...Christos Manios
 

Similar to buildingxmlbasedapplications-180322042009.pptx (20)

Xml and xml processor
Xml and xml processorXml and xml processor
Xml and xml processor
 
treeview
treeviewtreeview
treeview
 
treeview
treeviewtreeview
treeview
 
DOM-XML
DOM-XMLDOM-XML
DOM-XML
 
SAX - Android Development
SAX - Android DevelopmentSAX - Android Development
SAX - Android Development
 
IOC + Javascript
IOC + JavascriptIOC + Javascript
IOC + Javascript
 
0001 Genero Terms
0001 Genero Terms0001 Genero Terms
0001 Genero Terms
 
0001 Genero Terms
0001 Genero Terms0001 Genero Terms
0001 Genero Terms
 
Validating Xml
Validating XmlValidating Xml
Validating Xml
 
Working with xml data
Working with xml dataWorking with xml data
Working with xml data
 
04 sm3 xml_xp_07
04 sm3 xml_xp_0704 sm3 xml_xp_07
04 sm3 xml_xp_07
 
Unit 2
Unit 2 Unit 2
Unit 2
 
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
 
epicenter2010 Open Xml
epicenter2010   Open Xmlepicenter2010   Open Xml
epicenter2010 Open Xml
 
uptu web technology unit 2 Xml2
uptu web technology unit 2 Xml2uptu web technology unit 2 Xml2
uptu web technology unit 2 Xml2
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)
 
HTML literals, the JSX of the platform
HTML literals, the JSX of the platformHTML literals, the JSX of the platform
HTML literals, the JSX of the platform
 
Code Documentation. That ugly thing...
Code Documentation. That ugly thing...Code Documentation. That ugly thing...
Code Documentation. That ugly thing...
 
CTDA Workshop on XML and MODS
CTDA Workshop on XML and MODSCTDA Workshop on XML and MODS
CTDA Workshop on XML and MODS
 
Basics of XML
Basics of XMLBasics of XML
Basics of XML
 

Recently uploaded

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 

Recently uploaded (20)

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 

buildingxmlbasedapplications-180322042009.pptx

  • 1. BUILDING XML- BASED APPLICATIONS Parsing XML – using DOM, SAX Prepared By: Prabu.U – XML Transformation and XSL – XSL Formatting – Modeling Databases in XML
  • 2. Parsing XML Using Document Object Model Prepared By: Prabu.U  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)
  • 3. What Is DOM, Anyway? Prepared By: Prabu.U  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++.
  • 4. What DOM Is Not ? Prepared By: Prabu.U  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.
  • 5. Why Do I Need DOM? Prepared By: Prabu.U  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.
  • 6. Why Do I Need DOM? Prepared By: Prabu.U  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.
  • 7. Disadvantages of Using DOM Prepared By: Prabu.U  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.
  • 8. DOM Core Prepared By: Prabu.U <purchase-order> <customer>James Bond</customer> <merchant>Spies R Us</merchant> <items> <item>Night vision camera</item> <item>Vibrating massager</item> </items> </purchase-order>
  • 12. 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”); } }
  • 13. 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); }
  • 14. 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() + “>”); }
  • 15. Prepared By: Prabu.U public static void main(String args[]) throws Exception { SimpleWalker sw = new SimpleWalker(); sw.parse(args[0]); sw.printAllElements(); } } // class SimpleWalker
  • 16. 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>
  • 17. 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>
  • 18. 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().
  • 19. 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() + “>”); } }
  • 20. 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>
  • 21. DOM Traversal and Range Prepared By: Prabu.U  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.
  • 22. Traversal Prepared By: Prabu.U  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.
  • 24. Traversal Prepared By: Prabu.U <?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>
  • 25. Traversal Prepared By: Prabu.U 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()); }
  • 26. 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
  • 27. Traversal Prepared By: Prabu.U OUTPUT: Root element is library Moby Dick The Last Trail The Last Lion, Winston Spencer Churchill
  • 28. Range Prepared By: Prabu.U  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.
  • 30. Other DOM Implementations Prepared By: Prabu.U  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.
  • 31. JDOM Prepared By: Prabu.U  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.
  • 32. 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.
  • 33. 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
  • 34. 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
  • 35. Defining a Schema for the XML Document rental_property.dtd Prepared By: Prabu.U
  • 36. Creating the JAXB Binding Schema rental_property.xjs (for XML Java schema) Prepared By: Prabu.U
  • 37. Generating the JAXB Classes Based on Schemas Prepared By: Prabu.U
  • 38. Generating the JAXB Classes Based on Schemas Prepared By: Prabu.U 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.
  • 39. 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
  • 40. 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
  • 41. What Is SAX, Anyway? Prepared By: Prabu.U  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.
  • 42. What Is SAX, Anyway? Prepared By: Prabu.U  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.
  • 43. What SAX Is Not ? Prepared By: Prabu.U  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.
  • 44. Why Do I Need SAX? Prepared By: Prabu.U  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).
  • 45. SAX vs. DOM Prepared By: Prabu.U 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.
  • 46. SAX vs. DOM Prepared By: Prabu.U 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.
  • 47. SAX vs. DOM Prepared By: Prabu.U 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.
  • 48. Disadvantages Prepared By: Prabu.U  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.
  • 49. Disadvantages Prepared By: Prabu.U  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.
  • 50. SAX Versions Prepared By: Prabu.U  The first version, SAX 1.0, was released in May 1998.  It provided the basic functionality needed to attributes, text, and to manage errors. read elements,  There was also some DTD support.
  • 51. SAX Versions Prepared By: Prabu.U  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.
  • 52. SAX Basics Prepared By: Prabu.U <?xml version=”1.0” encoding=”UTF-8”?> <fiction> <book author=”Herman Melville”>Moby Dick</book> </fiction>
  • 53. SAX Basics Prepared By: Prabu.U  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.
  • 54. SAX Basics Prepared By: Prabu.U  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
  • 55. SAX Packages Prepared By: Prabu.U  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
  • 62. Working with SAX Prepared By: Prabu.U 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 + “>”); }
  • 63. Working with SAX Prepared By: Prabu.U 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); } }
  • 66. library.xml Prepared By: Prabu.U <?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>
  • 67. Output from SAXDemo Prepared By: Prabu.U ***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***
  • 70. XML Transformation and XSL Prepared By: Prabu.U  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
  • 71. XSL Technologies Prepared By: Prabu.U  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.
  • 72. XSLT for Document Publishing Prepared By: Prabu.U  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
  • 73. XSLT for Document Publishing Prepared By: Prabu.U  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.  Agrowing number of mobile phones and PDAs support the Wireless Application Protocol (WAP).
  • 74. XSLT for Document Publishing Prepared By: Prabu.U  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.
  • 75. Publishing documents with XSLT Prepared By: Prabu.U
  • 76. Sending data to the XSLT processor Prepared By: Prabu.U  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.
  • 77. Sending data to the XSLT processor Prepared By: Prabu.U
  • 78. Creating the XSL Style Sheet 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>
  • 79. Creating the XML Document Prepared By: Prabu.U <?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>
  • 80. Getting Started with XSLT Prepared By: Prabu.U
  • 81. The Missing Piece: The XSLT Processor Prepared By: Prabu.U
  • 82. 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.
  • 83. 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.
  • 85. 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.
  • 87. Implementing Client-Side XSLT Processing Prepared By: Prabu.U 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>
  • 88. 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>
  • 89. XSLT rendered in a Web browser Prepared By: Prabu.U
  • 90. Implementing Server-Side XSLT Processing Prepared By: Prabu.U  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).
  • 91. ASP: Server-Side XSLT Processing Prepared By: Prabu.U  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.
  • 92. 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)) %>
  • 94. JSP: Server-Side XSLT Processing Prepared By: Prabu.U  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:
  • 95. JSP: Server-Side XSLT Processing Prepared By: Prabu.U  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.
  • 96. 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” />
  • 97. XSL for Business-to-Business (B2B) Communication Prepared By: Prabu.U  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.
  • 99. XSL for Business-to-Business (B2B) Communication Prepared By: Prabu.U  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.
  • 100. 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.
  • 101. 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>
  • 102. 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>
  • 103. Creating the XSL Style Sheet Prepared By: Prabu.U  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>
  • 104. Creating the XSL Style Sheet Prepared By: Prabu.U  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” />
  • 105. Creating the XSL Style Sheet Prepared By: Prabu.U  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>
  • 106. 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>
  • 107. 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>
  • 108. XSL Formatting Objects XSL-FO Formatting Engines Prepared By: Prabu.U
  • 109. Basic Document Structure Prepared By: Prabu.U  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>
  • 110. Basic Document Structure Prepared By: Prabu.U  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
  • 111. Page Master: <fo:page-master> Prepared By: Prabu.U  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>
  • 112. Components of the page master Prepared By: Prabu.U
  • 113. Five regions of a page Prepared By: Prabu.U
  • 114. Five regions of a page Prepared By: Prabu.U 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>
  • 115. Page Master Set: <fo:page-master-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>
  • 116. Page Master Set: <fo:page-master-set> Prepared By: Prabu.U  Adocument 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:
  • 117. 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>
  • 118. Page Sequences: <fo:page-sequence> Prepared By: Prabu.U  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.
  • 119. Page Sequences: <fo:page-sequence> Prepared By: Prabu.U  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.
  • 120. Page Sequences: <fo:page-sequence> Prepared By: Prabu.U  Abody 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.
  • 121. 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>
  • 122. 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>
  • 123. Page Headers and Footers Prepared By: Prabu.U 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>
  • 124. 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>
  • 125. 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>
  • 126. 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>
  • 127. 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>
  • 128. Graphics Prepared By: Prabu.U  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.
  • 129. Graphics Prepared By: Prabu.U 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>
  • 130. Tables Prepared By: Prabu.U  XSL-FO has rich support for structuring tabular data.  In fact, there are many similarities between HTML tables and XSL-FO tables.
  • 131. Comparing HTML Table Elements and XSL-FO Table Elements Prepared By: Prabu.U
  • 132. 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”/>
  • 133. 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>
  • 134. 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>
  • 135. 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>
  • 138. Modeling Databases in XML Prepared By: Prabu.U
  • 139. 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 r Pe p a ar e d cB cy e:P sr a sb u .. U JAXB Solution
  • 140. Reviewing the Database Schema Prepared By: Prabu.U
  • 141. Reviewing the Database Schema Prepared By: Prabu.U
  • 142. Constructing the Desired XML Document Prepared By: Prabu.U
  • 143. Constructing the Desired XML Document Prepared By: Prabu.U
  • 144. rental_property.dtd <!ELEMENT rental_property_list (rental_property)* > <!ELEMENT rental_property (prop_id, name, square_footage, bedrooms, bath, price, contact)> address, <!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 (#P Pr e Cp a r De dB Ay :TP r a Ab u . )U > Defining a Schema for the XML Document
  • 145. <!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
  • 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 JAXB Classes Based on Schemas Prepared By: Prabu.U
  • 148. Developing a Data Access Object (DAO) Prepared By: Prabu.U
  • 150.  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
  • 151.  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
  • 152. 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); }
  • 153. Prepared By: Prabu.U public static void main(String[] args) { try { TestApp myApp = new TestApp(); myApp.process(); } catch (Exception exc) { exc.printStackTrace(); } }
  • 154. Converting the XML Data 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 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 </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 select=”address/state” />