RAMCO INSTITUTE OF TECHNOLOGY Department of Computer Science and Engineering Academic Year: 2019- 2020 (Odd Semester
1. 1
RAMCO INSTITUTE OF TECHNOLOGY
Department of Computer Science and Engineering
Academic Year: 2019- 2020 (Odd Semester)
------------------------------------------------------------------------------------------------------------------
Degree, Semester & Branch: VII Semester B.E. Computer Science and Engineering.
Course Code & Title: IT6801 Service Oriented Architecture.
Name of the Faculty member: Dr.M.Kaliappan, Associate Professor/CSE
----------------------------------------------------------------------------------------------------------------
UNIT-II - BUILDING XML- BASED APPLICATIONS
Parsing XML – using DOM, SAX,XML Transformation, XSL – XSL Formatting ,
Modeling Databases in XML
---------------------------------------------------------------------------------------------------------------------------
2.1 DOM (Document Object Model) (2 marks)
• DOM is a standard application programming interface (API) to access and manipulate
XML documents in memory.
• DOM is a tree structure that represents elements, attributes, and content access
elements and delete, add, or edit content and attributes.
• DOM interfaces are defined independent of any particular programming language. DOM
code can write any programming language, such as Java, ECMAScript (a standardized
version of JavaScript/JScript), or C++.
Why Do Need DOM? (2 marks)
• The main reason for using DOM is to access or modify an XML document
programmatically.
• 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
Disadvantages of Using DOM (2 marks)
• 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.
• The DOM API is too complex.
• DOM is not practical for small devices such as PDAs and cellular phones
Simple XML documents
<purchase-order>
<customer>James Bond</customer>
<merchant>Spies R Us</merchant>
<items>
<item>Night vision camera</item>
<item>Vibrating massager</item>
</items>
</purchase-order>
2. 2
DOM Interfaces (2 marks)
DOM interfaces are defined independent of any particular programming language. so that they
are language neutral.
Interface Description
Node It can be an element, attribute, text, and so on, and contains methods for
traversing a DOM tree
NodeList An ordered collection of Nodes.
Document An Node representing an entire document. It contains the root Node
Element A Node representing an XML element
Attr A Node representing an XML attribute
CharacterData A Node representing character data
Text A CharacterData node representing text
NamedNodeMap An unordered collection of Nodes that can be accessed by name and used
with attributes
DOMException An exception raised upon failure of an operation
Figure: Interface relationships
3. 3
Java Bindings (2 marks)
The Java bindings are sets of Java source files containing Java interfaces, and they map exactly to
the DOM interfaces.
Explain about DOM parser with example (12-marks)
or
Write a SimpleWalker.java to print the root and recursively print all child node names using
getNodeName() from the Node interface. Use a library.xml for traversing. (12-marks)
DOM is a standard application programming interface (API) to access and manipulate XML
documents in memory.
DOM is a tree structure that represents elements, attributes, and content access elements and
delete, add, or edit content and attributes
import java.io.*;
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();
// enables applications to obtain a parser that produces DOM object trees from XML
docBuilder = dbf.newDocumentBuilder();
}
public void parse(String fileName) throws Exception {
Document doc = docBuilder.parse(new FileInputStream(fileName));
// docBuilder loading and parsing an XML file, doc itself is a node
root = doc.getDocumentElement(); // get the root element
System.out.println(“Root element is “ + root.getNodeName());
}
public void printAllElements() throws Exception {
printElement(“”, root);
}
public void printElement(String indent, Node aNode) {
System.out.println(indent + “<” + aNode.getNodeName() + “>”);
Node child = aNode.getFirstChild();
while (child != null) {
printElement(indent + “t”, child); // recursively call all child node
child = child.getNextSibling();
}
System.out.println(indent + “</” + aNode.getNodeName() + “>”);
}
public static void main(String args[]) throws Exception {
SimpleWalker sw = new SimpleWalker();
sw.parse(args[0]);
sw.printAllElements();
}
4. 4
}
Ex:
<?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>
Sample output
Root element is library
<library>
<#text>
</#text>
<fiction>
<#text>
</#text>
<book> ----
The following method is used to print the content of the document.
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() + “>”);
}
}
Output:
Root element is library
<library>
<fiction>
<book>
Moby Dick
---
5. 5
2.2 DOM Traversal (Explain about DOM traversal with Example-08 marks)
• Traversal is a convenient way to walk through a DOM tree and select specific nodes.
This is useful to find certain elements and perform operations on them.
Interface Description
NodeIterator Used to walk through nodes linearly. Represents a subtree
as a linear list
TreeWalker Represents a subtree as a tree view
NodeFilter Can be used in conjunction with NodeIterator and
TreeWalker to select specific nodes
DocumentTraversal Contains methods to create NodeIterator and TreeWalker instances
Ex: IteratorApp.java
import javax.xml.parsers.*;
public class IteratorApp {
protected DocumentBuilder docBuilder;
protected Document document;
protected Element root;
public IteratorApp() throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
docBuilder = dbf.newDocumentBuilder();
DOMImplementation domImp = docBuilder.getDOMImplementation();
if (domImp.hasFeature(“Traversal”, “2.0”)) {
System.out.println(“Parser supports Traversal”);
}
}
public void parse(String fileName) throws Exception {
document = docBuilder.parse(new FileInputStream(fileName));
root = document.getDocumentElement();
System.out.println(“Root element is “ + root.getNodeName());
}
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();
}
}
public static void main(String args[]) throws Exception {
IteratorApp ia = new IteratorApp();
ia.parse(args[0]);
ia.iterate();
}
}
6. 6
NameNodeFilter.java
import org.w3c.dom.*;
import org.w3c.dom.traversal.*;
public class NameNodeFilter implements NodeFilter {
protected String name;
public NameNodeFilter(String inName) {
name = inName;
}
public short acceptNode(Node n) {
if (n.getNodeName().equals(name)) {
return FILTER_ACCEPT;
} else {
return FILTER_REJECT;
}
}
}
Output:
output from IteratorApp:
Parser supports MutationEvents
Root element is library
Moby Dick
The Last Trail
The Last Lion, Winston Spencer Churchill
2.3 Creating XML file using DOM interface. (12 Marks)
public class XMLDOMParser {
public static final String xmlFilePath = "C:UsersAdministratorDesktopfilesxmlfile1.xml";
public static void main(String argv[]) {
try {
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
// root element
Element root = document.createElement("company");
document.appendChild(root);
// employee element
Element employee = document.createElement("employee");
root.appendChild(employee);
// set an attribute to staff element
Attr attr = document.createAttribute("id");
attr.setValue("10");
7. 7
employee.setAttributeNode(attr);
// firstname element
Element firstName = document.createElement("firstname");
firstName.appendChild(document.createTextNode("James"));
employee.appendChild(firstName);
// lastname element
Element lastname = document.createElement("lastname");
lastname.appendChild(document.createTextNode("Harley"));
employee.appendChild(lastname);
// email element
Element email = document.createElement("email");
mail.appendChild(document.createTextNode("james@example.org"));
employee.appendChild(email);
// department elements
Element department = document.createElement("department");
department.appendChild(document.createTextNode("Human Resources"));
employee.appendChild(department);
// create the xml file and transform the DOM Object to an XML File
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(xmlFilePath));
transformer.transform(domSource, streamResult);
System.out.println("Done creating XML File");
2.4 Parsing XML using SAX (Examine SAX parsing for library XML document.(16 marks)
• SAX
– SAX is an event-based 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.
– Build a content handler by creating a Java class that implements the ContentHandler
interface in the org.xml.sax package.
– Register it with a SAX XMLReader, set up the input source, and start the parser. Next,
the methods in content handler will be called when the parser encounters elements, text,
and other data
8. 8
Library.xml
<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE library SYSTEM “library.dtd”>
<library>
<fiction>
<book author=”Herman Melville”>Moby Dick</book>
<book author=”Zane Grey”>The Last Trail</book>
</fiction>
<biography>
<book author=”William Manchester”>
The Last Lion, Winston Spencer Churchill
</book>
</biography>
<science>
<book author=”Hecht, Zajac”>Optics</book>
</science>
</library>
ContentHandler methods
• start document
• start element: fiction
• start element: book (including attributes)
• characters: Moby Dick
• end element: book
• end element: fiction
• end document
SaxDemo.java
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,
9. 9
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 + “>”);
}
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);
}
}
Output
***Start of Document***
<library>
10. 10
<fiction>
<book author=’Herman Melville’>
Moby Dick
</book>
--
--
***End of Document***
2.5 SAX validating parser
Explain about SAX validating parser (16 marks)
or
Create a Document Type Definition for library. Write a Java code for SAX validating parser to
determine whether a library XML document is valid based on a library Document Type
Definition.(16 marks)
• Validation
– SAX parsers come in two varieties: validating and non-validating.
– Validating parsers can determine whether an XML document is valid based on a
Document Type Definition (DTD) or Schema.
library.dtd—DTD File
<?xml version=”1.0” encoding=”US-ASCII”?>
<!ELEMENT library (fiction|biography|science)*>
<!ELEMENT fiction (book)+>
<!ELEMENT biography (book)+>
<!ELEMENT science (book)+>
<!ELEMENT book (#PCDATA)>
<!ATTLIST book author CDATA #REQUIRED>
SAXValidator.java
public class SAXValidator extends DefaultHandler {
private boolean valid;
11. 11
private boolean wellFormed;
public SAXValidator() {
valid = true;
wellFormed = true;
}
public void startDocument() {
System.out.println(“***Start of Document***”);
}
public void endDocument() {
System.out.println(“***End of Document***”);
}
public void error(SAXParseException e) {
valid = false;
}
public void fatalError(SAXParseException e) {
wellFormed = false;
}
public void warning(SAXParseException e) {
valid = false;
}
public boolean isValid() {
return valid;
}
public boolean isWellFormed() {
return wellFormed;
}
public static void main(String args[]) throws Exception {
if (args.length != 1) {
System.err.println(“Usage: java SAXValidate <xml-file>”);
System.exit(1);
}
XMLReader parser = XMLReaderFactory.createXMLReader(
“org.apache.xerces.parsers.SAXParser”);
parser.setFeature(“http://xml.org/sax/features/validation”, true);
SAXValidator handler = new SAXValidator();
parser.setContentHandler(handler);
parser.setErrorHandler(handler);
parser.parse(new InputSource(new FileReader(args[0])));
if (!handler.isWellFormed()) {
System.out.println(“Document is NOT well formed.”);
}
if (!handler.isValid()) {
System.out.println(“Document is NOT valid.”);
}
if (handler.isWellFormed() && handler.isValid()) {
12. 12
System.out.println(“Document is well formed and valid.”);
}
}
}
Output
***Start of Document***
***End of Document***
Document is NOT valid.
2.5 SAX vs. DOM (2 marks)
DOM SAX
The DOM parses XML in space SAX parses XML in time
DOM API are too complex SAX is a much lower level API
DOM is an in-memory tree structure of an
XML document. Large documents can take up
a lot of memory
SAX is an event-based API, SAX parsers read
documents when elements, text, comments,
and other data of interest are found.
Disadvantages of SAX (2 marks)
• SAX can be a bit harder to visualize compared to DOM because it is an event-driven
model.
• SAX implementations are read-only parsers
• There is no formal specification for SAX
2.6 XSL technology
• XSL technology is used for document publishing and B2B communication
– The XSL Transformation Language (XSLT)
– The XSL Formatting Object Language (XSL-FO)
2.6.1 XSL Transformation Language (XSLT) (16 marks)
– XSLT is used to convert an XML document to another format.
– XSL-FO provides a way of describing the presentation of an XML document.
– XSL convert the XML to an HTML file, PDF document, or other format.
• 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.
13. 13
• An XSLT processor is responsible for applying the rules defined in the style sheet to the
input XML document
XSLT 1.0 Processors
Company Product
Apache Xalan-J 1.2.2
Microsoft MS XML Parser 3.0
Sun Microsystems JAXP 1.1
Two techniques are available for performing the XSLT processing:
• client-side processing
• Server-side processing.
Client-side processing
Client-side XSLT processing occurs in a Web browser. The Web browser includes an
XSLT processor and retrieves the XML document and XSL style sheet.
Disadvantage
• Web browser must provide XSLT support.
• 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
• Server-side XSLT processing
• Server-side XSLT processing occurs on the Web server or application server.
• A server side 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.
• An advantage of the server-side technique is browser independence.
14. 14
2.6.1.1 Implementing Client-Side XSLT Processing
Or
With example show how XSLT can transform an XML document into HTML (16 marks)(Nov-
2016)
• The XML document requires a special processing instruction to reference the XSL style sheet.
• The processing instruction is <?xml-stylesheet>, and it has two attributes: type and href.
– The type attribute specifies the content type of the document to be retrieved (in
this case, text/xsl).
– The href attribute is a URL reference to the style sheet.
• Syntax:
<?xml-stylesheet type=”text/xsl” href=”book_view.xsl”?>
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 …….
</summary>
</book>
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” />
<b>By: </b> <xsl:value-of select=”author” />
<b>Cost: </b> <xsl:value-of select=”price” />
<b>Category: </b> <xsl:value-of select=”category” />
15. 15
<b>Description</b> <p/>
<i> <xsl:value-of select=”summary” /> </i>
</body></html>
</xsl:template>
</xsl:stylesheet>
To get the output, open the book.xml document in browser.
Output
2.6.1.2 Implementing Server-Side XSLT Processing
• XSLT processing in implementing in server-side with Microsoft’s Active Server Pages (ASP) and
Sun Microsystems’ JavaServer Pages (JSP).
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))
%>
Output
16. 16
2.6.1.2.1 JSP: Server-Side XSLT Processing
• In order to perform the server side processing with JSP, you will need to install the Java
Software Development Kit (SDK) along with a compliant JSP server container.
• Apache Tomcat Server 4. Apache Tomcat 4 is the implementation for JSP 1.2 and Java
Servlets 2.3
• JSP program
<%@ taglib uri=”http://jakarta.apache.org/taglibs/xsl-1.0” prefix=”jakarta” %>
<jakarta:apply xml=”book.xml” xsl=”book_view.xsl” />
The Apache <jakarta:apply> tag provides the XSLT processing
2.6.2 Advanced Features of XSLT
• Looping
• Sorting
• Conditional
• Filter
2.6.2.1 Looping
• The XSLT element <xsl:for-each> is used for looping through a list of elements.
• The <xsl:for-each> element is commonly used in the Web development world to
convert an XML document to an HTML table.
syntax for <xsl:for-each>:
<xsl:for-each select=node-set-expression>
<!-- content -->
</xsl:for-each>
Design an XSL style sheet to convert the XML document to an HTML table. Write a XSL to
performs a loop for each <book> element in the <booklist> element.(8 marks)
Booklist.xml
<?xml version=”1.0”?>
<booklist>
<book>
<author>Michael Daconta et al</author>
<title>XML Development with Java 2</title>
<category>Java</category>
<price currency=”USD”>37.99</price>
</book>
<book>
<author>Mark Grand</author>
<title>Patterns in Java</title>
<category>Java</category>
17. 17
<price currency=”USD”>44.99</price>
</book>
<book>
<author>Richard Monson-Haefel</author>
<category>Java</category>
<price currency=”USD”>34.95</price>
</book>
</booklist>
booklist_loop.xsl
<?xml version=”1.0”?>
<xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0”>
<xsl:template match=”/”> // search start from root
<html><body>
<h3>Looping Example</h3>
<hr></hr>
<table border=”1” cellpadding=”5”>
<tr>
<th>Author</th>
<th>Title</th>
<th>Category</th>
<th>Price</th>
</tr>
<!-- Perform loop for each book in the book list -->
<xsl:for-each select=”booklist/book” > //iterate from book element
<tr>
<td> <xsl:value-of select=”author” /> </td>
<td> <xsl:value-of select=”title” /> </td>
<td> <xsl:value-of select=”category” /> </td>
<td> <xsl:value-of select=”price” /> </td>
</tr>
</xsl:for-each>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet>
book_test.jsp
18. 18
<%@ taglib uri=”http://jakarta.apache.org/taglibs/xsl-1.0” prefix=”jakarta” %>
<jakarta:apply xml=”booklist.xml” xsl=”/booklist_loop.xsl” />
2.6.2.2 Sorting
• In XSLT, the <xsl:sort> element is used for sorting the XML data. It is possible to sort based on
a single key or multiple keys.
• The syntax for the <xsl:sort> :
<xsl:sort
select = string-expression
order = { “ascending” | “descending” }
data-type = { “text” | “number” }
case-order = {“upper-first” | “lower-first” }
lang = { nmtoken } />
Sort Order: Ascending or Descending
By default, the information is sorted in ascending order. Set the order attribute to descending for
a descending sort.
Ex: Write a XSL program to sort the books in booklist.xml by price. (8 marks)
<?xml version=”1.0”?>
<xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0”>
<xsl:template match=”/”>
<html><body>
<h3>Sorting Example: By Price</h3>
<hr></hr>
19. 19
<table border=”1” cellpadding=”5”>
<tr>
<th>Author</th>
<th>Title</th>
<th>Category</th>
<th>Price</th>
</tr>
<!-- Perform loop for each book in the book list -->
<xsl:for-each select=”booklist/book” >
<xsl:sort select=”price” order=”ascending” data-type=”number” />
<tr>
<td> <xsl:value-of select=”author” /> </td>
<td> <xsl:value-of select=”title” /> </td>
<td> <xsl:value-of select=”category” /> </td>
<td> <xsl:value-of select=”price” /> </td>
</tr>
</xsl:for-each>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet>
20. 20
2.6.2.2.1 Sorting with Multiple Keys
• To sort using multiple keys.
• Ex: sort the books by category and then by price.
– This is accomplished by inserting multiple <xsl:sort> elements within an <xsl:for-
each> element
<?xml version=”1.0”?>
<xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0”>
<xsl:template match=”/”>
<html><body>
<h3>Sorting Example: By Price</h3>
<hr></hr>
<table border=”1” cellpadding=”5”>
<tr>
<th>Author</th>
<th>Title</th>
<th>Category</th>
<th>Price</th>
</tr>
<!-- Perform loop for each book in the book list and Sorting with Multiple Keys -->
<xsl:for-each select=”booklist/book” >
<xsl:sort select=”category” />
<xsl:sort select=”price” data-type=”number” />
<tr>
<td> <xsl:value-of select=”author” /> </td>
<td> <xsl:value-of select=”title” /> </td>
<td> <xsl:value-of select=”category” /> </td>
<td> <xsl:value-of select=”price” /> </td>
</tr>
</xsl:for-each>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet>
21. 21
2.6.2.3 Conditionals
• During an XSLT transformation, the style sheet can perform conditional tests on the data.
• XSLT contains a very simple if-then conditional. The syntax for the <xsl:if> element
<xsl:if test=Boolean-expression>
<!-- content -->
</xsl:if>
Consider a booklist.xml document contains book details. Write a XSL program to display the all
book. The background color of the row is set to red for all Fiction-Thriller books in book list (8
marks)
<xsl:for-each select=”booklist/book” >
<tr>
<xsl:if test=”category=’Fiction-Thriller’”>
<xsl:attribute name=”bgcolor”>red</xsl:attribute>
</xsl:if>
<td> <xsl:value-of select=”author” /> </td>
<td> <xsl:value-of select=”title” /> </td>
<td> <xsl:value-of select=”category” /> </td>
<td> <xsl:value-of select=”price” /> </td>
</tr>
</xsl:for-each>
22. 22
2.6.2.4 Filters
• XSLT can filter the data based on a given expression.
• Ex:
– XSL code to filter the data to contain only Java books.
<xsl:for-each select=”booklist/book*category=’Java’+” >
<tr>
<td> <xsl:value-of select=”author” /> </td>
<td> <xsl:value-of select=”title” /> </td>
<td> <xsl:value-of select=”category” /> </td>
<td> <xsl:value-of select=”price” /> </td>
</tr>
</xsl:for-each>
2.6.3 XSL Formatting Objects
• XSL-FO assists with the printing and displaying of XML data.
• XSL-FO provides the document layout and structure. This includes the dimensions of the
output document, including page headers, footers, and margins.
• XSL-FO also allows the developer to define the formatting rules for the content, such as
font, style, color, and positioning.
• XSL-FO formatting engines specification.
– XEP
– Apache XSL-FOP
– iText
– Unicorn
An XML-FO document follows the syntax rules of XML, It is well formed documnet.
XSL-FO elements use the following namespace:
o http://www.w3.org/1999/XSL/Format
<?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>
23. 23
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
2.6.3.1 Page Master: <fo:page-master>
• The page master describes the page size and layout.
• The page master contains the dimensions for a page, including width, height, and
margins.
• The page master is similar to a slide master in Microsoft PowerPoint.
• The <fo:simple-page-master> element defines the layout of a page. The following
<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>
• Each page is divided into five regions. Regions serve as containers for the document content.
• 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”/>
24. 24
<fo:region-after extent=”0.5in”/>
</fo:simple-page-master>
2.6.3.2 Page Master Set: <fo:page-master-set>
• A document can be composed of multiple pages, each with its own dimensions. The page
master set refers to the collection of page masters.
<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>
2.6.3.3 Page Sequences: <fo:page-sequence>
• A page sequence defines a series of printed pages. Each page sequence refers to a page
master for its dimensions.
• The page sequence contains the actual content for the document.
• The <fo:page-sequence> element contains
– <fo:static-content> and <fo:flow> elements.
25. 25
• The <fo:static-content> element is used for page headers and footers.
• The <fo:flow> element contains a collection of text blocks.
• A body of text is defined using the <fo:block> element.
• The <fo:block> element is a child element of <fo:flow>.
<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>
<!-- 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 -----
</fo:block>
</fo:flow>
</fo:page-sequence>
26. 26
2.6.3.4 Page Headers and Footers
• The <fo:static-content> element is used to set up page headers and footers.
• The <fo:static-content> element is a component of <fo:page-sequence>.
Ex:
• Define a page header that contains the company name and current page number. Also,
define a footer that lists the company’s Web site. It composed of multiple pages to
illustrate the fact that the header and footer are repeated on each page.(12 marks)
<!-- 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>
<!-- 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>
27. 27
New pages are generated using <fo:block break-before=”page”>.
<!-- insert page break for second page -->
<fo:block break-before=”page”>
A page break is inserted before this block. ----
</fo:block>
2.6.3.5 Graphics
• XSL-FO also allows for the insertion of external graphic images.
• The graphic formats supported are dependent on the XSL-FO formatting engine. The
Apache-FOP formatting engine supports the popular graphics formats: GIF, JPEG, and
BMP.
• 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>
28. 28
2.6.3.6 FO-Tables
• XSL-FO has rich support for structuring tabular data.
<fo:table>
<!-- define column widths -->
<fo:table-column column-width=”120pt”/>
<fo:table-column column-width=”200pt”/>
<fo:table-column column-width=”80pt”/>
<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>
<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> </fo:table-body> </fo:table>
29. 29
2.6.3.7 Generating XSL-FO Tables Using XSLT ( 16 marks)
Or
The file, booklist.xml, contains a list of the books that extremely large and verbose. Create XSLT
to automatically generate the XSL-FO document. Also, develop an XSL style sheet that will
automatically construct the XSL-FO document. (16 marks)
XSL document.
<fo:root xmlns:fo=”http://www.w3.org/1999/XSL/Format”>
<fo:layout-master-set>
<!-- layout information -->
<fo:simple-page-master master-name=”simple”
page-height=”11in”
page-width=”8.5in”
margin-top=”1in”
margin-bottom=”2in”
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>
<!-- end: defines page layout -->
<fo:page-sequence master-name=”simple”>
<fo:flow flow-name=”xsl-region-body”>
<!-- this defines a level 1 heading with orange background -->
31. 31
</fo:table-cell>
<fo:table-cell>
<fo:block><xsl:value-of select=”price” /></fo:block>
</fo:table-cell>
</fo:table-row>
</xsl:for-each>
</fo:table-body>
</fo:table> </fo:flow>
</fo:page-sequence> </fo:root>
</xsl:template> </xsl:stylesheet>
Generating a PDF Document
• The first step involves XSLT processing the booklist.xml document with booklist_table.xsl.
• The second step involves converting the output of the XSLT conversion to a PDF file using
XSL-FO
• Follow these steps to generate the PDF document:
– 1. Open an MS-DOS window.
– 2. Set up the Java classpath by typing setpaths.
– 3. Execute Apache-FOP by typing the following:
> fop -xml booklist.xml -xsl booklist_table.xsl dyntable.pdf
32. 32
2.6.4. Integrating XML with Databases
• XML Database Solutions
• Modeling Databases in XML
2.6.4.1 XML Database Solutions
• IT come in two flavors
– database mapping
– native XML support
• XML Database Mapping
– The first type of XML database solution provides a mapping between the XML
document and the database fields.
– The system dynamically converts SQL result sets to XML documents. It may provide a
graphical tool to map the database fields to the desired XML elements.
– Other tools support a configuration file that defines the mapping. These tools
continue to store the information in relational database management system (RDBMS)
format.
Product Company
DB2 Extender IBM
SQL Server 2000 Microsoft
Oracle 8i & 9i Oracle
Native XML Support
• It stores the XML data in the document in its native format.
• Each product uses its own proprietary serialization technique to store the data. However,
when the data is retrieved, it represents an XML document
33. 33
2.6.4.2 Modeling Databases in XML ( 16 marks)
• Model a database in XML using Java. When we model a database, we provide an external
representation of the database contents.
• Ex: model the rental property database as an XML document.
• One possible solution is to use Java servlets and JDBC.
– Java servlets are server-side components that reside in a Web server or
application server.
– A key advantage to using servlets is the thin-client interface. The servlets handle
the request on the server side and respond by generating an HTML page
dynamically. This lowers the requirement on the client browser
JAXB (Java Architecture for XML data binding )
• JAXB provides a framework for representing XML documents as Java objects.
• JAXB framework guarantee that the documents processed by our system are well formed
or validating.
• unmarshaling
– Parse the XML documents into a Java object. This technique is referred to as
unmarshaling.
• marshaling
– The JAXB framework also parse the Java object into XML documents which is
referred to as marshaling
• JAXB is similar to DOM to create XML documents programmatically and perform
validation.
JAXB Solution
• In the JAXB solution, consider the model the rental property database as an XML
document. Develop the desired XML document based on an XML schema. After the XML
schema developed, create the JAXB binding schema. The JAXB binding schema contains
instructions on how to bind the XML schema to a Java class.
34. 34
• To summarize:
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
2.6.4.2.1 Reviewing the Database Schema
Rental Property Database Schema
Field Type
prop_num NUMBER
name VARCHAR2
street_address VARCHAR2
city VARCHAR2
state VARCHAR2
zip_code VARCHAR2
size_sq NUMBER
bed_count NUMBER
bath_count NUMBER
monthly_rent NUMBER
voice_phone VARCHAR2
fax_phone VARCHAR2
2.6.4.2.2 Constructing the Desired XML Document
Field XML Element Name
prop_num <prop_id>
name <name>
street_address <street>
city <city>
state <state >
zip_code <postal_code>
size_sq <square_footage>
bed_count <bedrooms>
bath_count <bath>
monthly_rent <price>
voice_phone <phone>
fax_phone <fax>
<rental_property>
35. 35
<prop_id>1</prop_id>
<name>The Meadows</name>
<address>
<street>251 Eisenhower Blvd</street>
<city>Houston</city>
<state>TX</state>
<postal_code>77033</postal_code>
</address>
<square_footage>500.0</square_footage>
<bedrooms>1.0</bedrooms>
<bath>1.0</bath>
<price>600</price>
<contact>
<phone>555-555-1212</phone>
<fax>555-555-1414</fax>
</contact>
</rental_property>
2.6.4.2.3 Defining a Schema for the XML Document
• The DTD schema format was chosen because JAXB 1.0 only supports DTDs
rental_property.dtd
<!ELEMENT rental_property_list (rental_property)*>
<!ELEMENT rental_property (prop_id, name, address, square_footage, bedrooms, bath,
price, contact)>
<!ELEMENT prop_id (#PCDATA)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT address (street, city, state, postal_code)>
<!ELEMENT street (#PCDATA)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT state (#PCDATA)>
<!ELEMENT postal_code (#PCDATA)>
<!ELEMENT square_footage (#PCDATA)>
<!ELEMENT bedrooms (#PCDATA)>
<!ELEMENT bath (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT contact (phone, fax)>
36. 36
<!ELEMENT phone (#PCDATA)>
<!ELEMENT fax (#PCDATA)>
2.6.4.2.4 Creating the JAXB Binding Schema
• The JAXB binding schema is an XML document that contains instructions on how to bind a
DTD to a Java class.
• JAXB binding schema define the
– names of the generated Java classes,
– map element names to specific properties in the Java class,
– provide the mapping rules for attributes. Elements should be converted to a Java
primitive type or class
rental_property.xjs (JAXB binding schema file for rental property)
<?xml version=”1.0” encoding=”ISO-8859-1” ?>
<!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>
2.6.4.2.5 Generating the JAXB Classes Based on Schemas
• JAXB provides a schema compiler for generating the Java source files. The schema
compiler takes as input the DTD and the JAXB binding schema
• >> java com.sun.tools.xjc.Main rental_property.dtd rental_property.xjs –d source_code
• This command generates the following source code :
– 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
38. 38
public void setAddress (Address _Address) {
this._Address = _Address;
if (_Address == null) {
invalidate();
}
}
public void marshal( Marshaller m) throws IOException
{
// code to output the XML document
}
public void unmarshal( Unmarshaller u) throws UnmarshalException
{
// code to read in the XML document
}
--
--
2.6.4.2.6 Developing a Data Access Object (DAO)
• A Data Access Object (DAO) provides access to the database via public methods.
• The goal of the DAO is to provide a higher level of abstraction for database access
• DAO encapsulates the complex JDBC and SQL calls.
• The DAO converts a result set to a collection of objects.
• Benefits of DAO
– By using a DAO, the implementation details of the database are hidden from the
application clients.
– A benefit of using the DAO is improved application maintenance. If the database
schema changes, such as a column name being modified, we only have to update
the DAO. No modifications are required to the client programs
RentalPropertyDAO
• The getRentalProperties() method submits a SQL query to the database and converts the
result set to a collection of JAXB RentalProperty objects
39. 39
public class RentalPropertyDAO {
protected Connection myConn;
/* Constructor for Setup the database connection, Use the default properties */
public RentalPropertyDAO() throws DAOException {
Try{
Class.forName(“sun.jdbc.odbc.JdbOdbcDriver”);
myConn = DriverManager.getConnection(”jdbc:odbc:RentalPropertyDSN”, ”uid”, “pwd”);
}
catch (Exception exc) { };
}
}
Clients can retrieve data from the database by calling the getRentalProperties()method
public RentalPropertyList getRentalProperties() throws DAOException {
RentalPropertyList RPList = new RentalPropertyList();
List Lobj = RPList.getList();
try {
Statement myStmt = myConn.createStatement();
String rentalSql = “SELECT * FROM rental_properties”;
ResultSet myRs = myStmt.executeQuery(rentalSql);
RentalProperty tempProperty = null;
// build a collection of JAXB RentalProperty objects
while (myRs.next()) {
tempProperty = createRentalProperty(myRs);
theList.add(tempProperty);
}
RPList.validate(); //to validate the new list
return RPList;
}
//The createRentalProperty method provides the mapping between database schema and object
protected RentalProperty createRentalProperty(ResultSet theRs) throws DAOException {
RentalProperty theProperty = new RentalProperty();
Address theAddress = new Address();
40. 40
Contact theContact = new Contact();
try {
// set the rental property number and name
theProperty.setPropId(theRs.getString(“prop_num”));
theProperty.setName(theRs.getString(“name”));
// set the address
theAddress.setStreet(theRs.getString(“street_address”));
theAddress.setCity(theRs.getString(“city”));
theAddress.setState(theRs.getString(“state”));
theAddress.setPostalCode(theRs.getString(“zip_code”));
theProperty.setAddress(theAddress);
// set the square footage, bedrooms, bath count and rent
theProperty.setSquareFootage(theRs.getDouble(“size_sq”));
theProperty.setBedrooms(theRs.getDouble(“bed_count”));
theProperty.setBath(theRs.getDouble(“bath_count”));
theProperty.setPrice(new BigDecimal(theRs.getDouble(“monthly_rent”)));
// set the contact information
theContact.setPhone(theRs.getString(“voice_phone”));
theContact.setFax(theRs.getString(“fax_phone”));
theProperty.setContact(theContact);
return theProperty;
}
Output: Rental property XML document
<?xml version=”1.0” encoding=”UTF-8”?>
<rental_property_list>
<rental_property>
<prop_id>1</prop_id>
<name>The Meadows</name>
<address>
<street>251 Eisenhower Blvd</street>
<city>Houston</city>
<state>TX</state>
<postal_code>77033</postal_code>
</address>
42. 42
<init-param>
<param-name>user</param-name>
<param-value>test</param-value>
</init-param>
<init-param>
<param-name>pass</param-name>
<param-value>test</param-value>
</init-param>
<load-on-startup/>
</servlet>
• The servlet reads the parameters and constructs the RentalPropertyDAO Data Access Object
in the init() method.
• The servlet handles HTTP GET requests, to override the doGet() method.
• Next, set up ServletOutputStream to retrieve a list of rental properties from
RentalPropertyDAO. The list is then marshaled to the ServletOutputStream object, out.
RentalXMLServlet.java
public class RentalXMLServlet extends HttpServlet {
public void init() throws ServletException {
// retrieve database connection parameters
String dbUrl = getInitParameter(“dbUrl”);
String driverName = getInitParameter(“driverName”);
String user = getInitParameter(“user”);
String pass = getInitParameter(“pass”);
// create an instance of the RentalPropertyDAO
myRentalDAO = new RentalPropertyDAO(driverName, dbUrl, user, pass);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
ServletOutputStream out = null;
RentalPropertyList theList = null;
response.setContentType(“text/xml”);
// Retrieve the servlet output stream
out = response.getOutputStream();
// Retrieve a list of rental properties
theList = myRentalDAO.getRentalProperties();
43. 43
// Marshal the list as an XML document
theList.marshal(out);
}
} //end of the servlet
44. 44
Application level questions:
1. Write a SimpleWalker.java to print the root and recursively print all child node names using
getNodeName() from the Node interface. Use a library.xml for traversing. (12-marks)(Refer
page no 3)
2. Create a Document Type Definition for library. Write a Java code for SAX validating parser to
determine whether a library XML document is valid based on a library Document Type
Definition.(16 marks)(Refer 2.5)
3. Design an XSL style sheet to convert the XML document to an HTML table. Write a XSL to
performs a loop for each <book> element in the <booklist> element.(8 marks) (Refer 2.6.2.1)
4. Consider a booklist.xml document contains book details. Write a XSL program to display the
all book. The background color of the row is set to red for all Fiction-Thriller books in book
list. (8 marks) (Refer 2.6.2.3)
5. Define a page header that contains the company name and current page number. Also,
define a footer that lists the company’s Web site. It composed of multiple pages to illustrate
the fact that the header and footer are repeated on each page.(12 marks) (Refer 2.6.3.4)
6. The file, booklist.xml, contains a list of the books that extremely large and verbose. Create
XSLT to automatically generate the XSL-FO document. Also, develop an XSL style sheet that
will automatically construct the XSL-FO document. (16 marks) (Refer 2.6.3.7)
7. Consider the model the rental property database as an XML document. Develop the desired
XML document based on an XML schema. After the XML schema developed, create the JAXB
binding schema. The JAXB binding schema contains instructions on how to bind the XML
schema to a Java class.(Refer 2.6.2.4)
8. Create a rental_view.xsl that contains the HTML template along with the XSLT constructs to
retrieve the data. XSL defines an HTML table with instructions to create a table row for each
rental property in the list.