You are on page 1of 39

Lesson 2

Programming web clients


Lesson 2: Programming web clients
_____________________________________________________________________________

2.1 Lesson Objectives

The Web 2.0 architecture offers new ways for major client side technologies to work together.
This lesson first explores the technologies used to create Web 2.0 applications. This includes a
detailed look at JavaScript and CSS (Cascading Style Sheets). Next, the lesson provides an
explanation of the XML (eXtensible Markup Language) , XML Schema datatypes and XSLT
constructs using easy to understand examples. The lesson also provides an understanding of
SAX and DOM parsers.

Building Rich Internet Applications with Adobe Flex 2-2


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

2.2 Client side programming

Client side programs are the programs on the World Wide Web (or simply Web) that are
executed client-side i.e. on the user’s browser, whereas the server side programs on the Web
are executed on the server machine which hosts that particular web application.
Client side programs provide dynamic behavior to the client by executing a program on the
browser. The most common purpose of client side programs is to verify the user data i.e.
whether the user entered appropriate data or not and to ensure whether the user filled
mandatory fields or not. The most common tools used for client side programming are scripting
languages like JavaScript, VBScript, Jscript, etc.

2.3 An overview of Javascript


JavaScript was developed by Brendan Eich at Netscape. JavaScript was first introduced and
deployed in the Netscape browser version 2.0B3 in December 1995. Like any other scripting
language Javascript is also a light-weight programming language, even though it provides
several features, few of the features are as follows:

A Great Programming Tool for HTML.


Professional Web designers are undoubtedly adept in using HTML and proficient in website
design but not necessarily skillful in computer programming. JavaScript is a programming tool
for such a situation. JavaScript is a powerful scripting language that helps HTML designers to
effectively and interactively design websites and web pages in a very simple and efficient way.

Simple to learn.
JavaScript is not a complex language like procedural and OO languages. It has simple
rules and procedures that make it easier to learn for programmers. Because of its simplicity it
became popular client-side scripting language.

Handles dynamic effects.


JavaScript has features to achieve dynamic effects in web pages. Using the features
available in JavaScript, the designer can decide to have dynamically placed text at run
time.

Browser detection.
This feature detects client browser. This feature of JavaScript helps to achieve independent
platforms. JavaScript can detect the type and version of browser the visitor is using and
programmatically switch the page to show customized pages designed for different browsers.
By using browser detection feature of JavaScript, the designer gets better control over the
browser.

Saves time.
JavaScript has the feature of validating data submitted by the client at the client side itself. This
helps in saving the processing time of the server because there is no need to transfer form data
from client to server several times.
Building Rich Internet Applications with Adobe Flex 2-3
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

DOM.
Client side JavaScript is embedded into HTML; this embedded JavaScript is used along with
DOM (Document Object Model) for control over the browser by means of objects.

Interpreted language
Javascript is an interpreted language, meaning that it can be executed without any compilation.

Structured programming
JavaScript supports almost all the structured programming features/syntax.

2.4 Javascript objects


Javascript is an Object-Oriented Programming language. Similar to any other OOP language,
javascript also provides built-in objects and also enables the programmer to define his/her own
objects. Here in the following sections we will discuss few built-in Javascript objects.

2.4.1 String
The String object is used to manipulate a string literal. The properties and methods of String
objects are shown below.

String object properties


Property Description
Constructor A reference to the function that created the object
Length Returns the number of characters in a string
Prototype Allows you to add properties and methods to the object

String object methods

Method Description
anchor() Creates an HTML anchor
big() Displays a string in a big font
blink() Displays a blinking string
bold() Displays a string in bold
charAt() Returns the character at a specified position
charCodeAt() Returns the Unicode of the character at a specified position
concat() Joins two or more strings
fixed() Displays a string as teletype text
fontcolor() Displays a string in a specified color
fontsize() Displays a string in a specified size
Building Rich Internet Applications with Adobe Flex 2-4
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

fromCharCode() Takes the specified Unicode values and returns a string


indexOf() Returns the position of the first occurrence of a specified string value in a
string
italics() Displays a string in italic
lastIndexOf() Returns the position of the last occurrence of a specified string value,
searching backwards from the specified position in a string
link() Displays a string as a hyperlink
match() Searches for a specified value in a string
replace() Replaces some characters with some other characters in a string
search() Searches a string for a specified value
slice() Extracts a part of a string and returns the extracted part in a new string
small() Displays a string in a small font
split() Splits a string into an array of strings
strike() Displays a string with a strikethrough
sub() Displays a string as subscript
substr() Extracts a specified number of characters in a string, from a start index
substring() Extracts the characters in a string between two specified indices
sup() Displays a string as superscript
toLowerCase() Displays a string in lowercase letters
toUpperCase() Displays a string in uppercase letters
toSource() Represents the source code of an object
valueOf() Returns the primitive value of a String object

Example 1: The following example prints the length of a given string.

<html>
<body>
<script type="text/javascript">
var txt="Good Morning";
document.write(“Length of the string=”+txt.length);
</script>
</body>
</html>

Running the above code will print ‘Length of the string=10’. (Type the code in an HTML
document and then render it using any web browser).

Example 2: The following example replaces the string “Morning” with “Evening”.

<html>
<body>
<script type="text/javascript">
var str="Good Morning";
Building Rich Internet Applications with Adobe Flex 2-5
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

document.write(str.replace(/Morning/,"Evening"));
</script>
</body>
</html>

Running the above code will print ‘Good Evening’. (Type the code in an HTML document and
then render it using any web browser).

2.4.2 Date
The Date object is used to work with data and time. The properties and methods of Date Object
are shown below.

Date object properties

Property Description
constructor A reference to the function that created the object
prototype Allows you to add properties and methods to the object

Date object methods

Method Description
Date() Returns today's date and time
getDate() Returns the day of the month from a Date object (from 1-31)
getDay() Returns the day of the week from a Date object (from 0-6)
getMonth() Returns the month from a Date object (from 0-11)
getFullYear() Returns the year, as a four-digit number, from a Date object
getYear() Returns the year, as a two-digit or a three/four-digit number, depending
on the browser. Use getFullYear() instead !!
getHours() Returns the hour of a Date object (from 0-23)
getMinutes() Returns the minutes of a Date object (from 0-59)
getSeconds() Returns the seconds of a Date object (from 0-59)
getMilliseconds() Returns the milliseconds of a Date object (from 0-999)
getTime() Returns the number of milliseconds since midnight Jan 1, 1970
getTimezoneOffset() Returns the difference in minutes between local time and Greenwich
Mean Time (GMT)
getUTCDate() Returns the day of the month from a Date object according to universal
time (from 1-31)
getUTCDay() Returns the day of the week from a Date object according to universal
time (from 0-6)
getUTCMonth() Returns the month from a Date object according to universal time (from
Building Rich Internet Applications with Adobe Flex 2-6
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

0-11)
getUTCFullYear() Returns the four-digit year from a Date object according to universal time
getUTCHours() Returns the hour of a Date object according to universal time (from 0-23)
getUTCMinutes() Returns the minutes of a Date object according to universal time (from 0-
59)
getUTCSeconds() Returns the seconds of a Date object according to universal time (from 0-
59)
getUTCMilliseconds() Returns the milliseconds of a Date object according to universal time
(from 0-999)
parse() Takes a date string and returns the number of milliseconds since
midnight of January 1, 1970
setDate() Sets the day of the month in a Date object (from 1-31)
setMonth() Sets the month in a Date object (from 0-11)
setFullYear() Sets the year in a Date object (four digits)
setYear() Sets the year in the Date object (two or four digits). Use setFullYear()
instead
setHours() Sets the hour in a Date object (from 0-23)
setMinutes() Set the minutes in a Date object (from 0-59)
setSeconds() Sets the seconds in a Date object (from 0-59)
setMilliseconds() Sets the milliseconds in a Date object (from 0-999)
setTime() Calculates a date and time by adding or subtracting a specified number of
milliseconds to/from midnight January 1, 1970
setUTCDate() Sets the day of the month in a Date object according to universal time
(from 1-31)
setUTCMonth() Sets the month in a Date object according to universal time (from 0-11)
setUTCFullYear() Sets the year in a Date object according to universal time (four digits)
setUTCHours() Sets the hour in a Date object according to universal time (from 0-23)
setUTCMinutes() Set the minutes in a Date object according to universal time (from 0-59)
setUTCSeconds() Set the seconds in a Date object according to universal time (from 0-59)
setUTCMilliseconds() Sets the milliseconds in a Date object according to universal time (from
0-999)
toSource() Represents the source code of an object
toString() Converts a Date object to a string
toGMTString() Converts a Date object, according to Greenwich time, to a string. Use
toUTCString() instead !!
toUTCString() Converts a Date object, according to universal time, to a string
toLocaleString() Converts a Date object, according to local time, to a string
UTC() Takes a date and returns the number of milliseconds since midnight of
January 1, 1970 according to universal time
valueOf() Returns the primitive value of a Date object

Building Rich Internet Applications with Adobe Flex 2-7


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

2.4.3 Array
The Array Object is a collection of multiple values. The properties and methods of Array object
are shown below.

Array object properties

Property Description
constructor A reference to the function that created the object
length Sets or returns the number of elements in an array
prototype Allows you to add properties and methods to the object

Array object methods

Method Description
concat() Joins two or more arrays and returns the result
join() Puts all the elements of an array into a string. The elements are
separated by a specified delimiter
pop() Removes and returns the last element of an array
push() Adds one or more elements to the end of an array and returns the new
length
reverse() Reverses the order of the elements in an array
shift() Removes and returns the first element of an array
slice() Returns selected elements from an existing array
sort() Sorts the elements of an array
splice() Removes and adds new elements to an array
toSource() Represents the source code of an object
toString() Converts an array to a string and returns the result
unshift() Adds one or more elements to the beginning of an array and returns the
new length
valueOf() Returns the primitive value of an Array object

2.4.4 Boolean
The Boolean object is a wrapper for a Boolean value (true, false). The properties and methods
of Boolean object are shown below.

Building Rich Internet Applications with Adobe Flex 2-8


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

Boolean object properties

Property Description
constructor A reference to the function that created the object
prototype Allows you to add properties and methods to the object

Boolean object methods

Method Description
toSource() Represents the source code of an object
toString() Converts a Boolean value to a string and returns the result
valueOf() Returns the primitive value of a Boolean object

2.4.5 Math
The Math object enables the programmer to perform several mathematical operations. The
properties and methods of the Math Object are as under.

Math object properties

Property Description
constructor A reference to the function that created the object
E Returns Euler's constant (approx. 2.718)
LN2 Returns the natural logarithm of 2 (approx. 0.693)
LN10 Returns the natural logarithm of 10 (approx. 2.302)
LOG2E Returns the base-2 logarithm of E (approx. 1.414)
LOG10E Returns the base-10 logarithm of E (approx. 0.434)
PI Returns PI (approx. 3.14159)
prototype Allows you to add properties and methods to the object
SQRT1_2 Returns the square root of 1/2 (approx. 0.707)
SQRT2 Returns the square root of 2 (approx. 1.414)

Math object methods

Method Description
abs(x) Returns the absolute value of a number
acos(x) Returns the arccosine of a number
asin(x) Returns the arcsine of a number
Building Rich Internet Applications with Adobe Flex 2-9
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2
radians
atan2(y,x) Returns the angle theta of an (x,y) point as a numeric value between -PI
and PI radians
ceil(x) Returns the value of a number rounded upwards to the nearest integer
cos(x) Returns the cosine of a number
exp(x) Returns the value of Ex
floor(x) Returns the value of a number rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of a number
max(x,y) Returns the number with the highest value of x and y
min(x,y) Returns the number with the lowest value of x and y
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds a number to the nearest integer
sin(x) Returns the sine of a number
sqrt(x) Returns the square root of a number
tan(x) Returns the tangent of an angle
toSource() Represents the source code of an object
valueOf() Returns the primitive value of a Math object

2.5 Regular Expressions


JavaScript 1.2 and later versions has built-in support for regular expressions. Most web
browsers support JavaScript 1.2. If you use JavaScript to validate user input on a web page at
the client side, using JavaScript's regular expression support will reduce the amount of code you
need to write. The following sections will help you to understand/learn what is a Regular
expression, how to define regular expressions, methods of the regular expression object, etc.

2.5.1 What is a regular expression?


A Regular Expression is a pattern that enables you to describe the type of string you want to
search inside some text or in other words the regular expression object is used to store the
search pattern.

2.5.2 How to define a regular expression?


Several constructs are used to define/construct a regular expression. Some of these contructs
are discussed in the following sections.

Building Rich Internet Applications with Adobe Flex 2-10


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

Character classes
Construct Matches
[abc] a, b, or c (simple class)
[^abc] Any character except a, b, or c (negation)
[a-zA-Z] a through z or A through Z, inclusive (range)
[a-d[m-p]] a through d, or m through p: [a-dm-p] (union)
[a-z&&[def]] d, e, or f (intersection)
[a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction)

Predefined character classes


Construct Matches
\d A digit: [0-9]
\D A non-digit: [^0-9]
\s A whitespace character: [ \t\n\x0B\f\r]
\S A non-whitespace character: [^\s]
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]

Boundary matchers
Character Matches
^ The beginning of a line
$ The end of a line
\b A word boundary
\B A non-word boundary
\A The beginning of the input
\G The end of the previous match
\Z The end of the input but for the final terminator, if any
\z The end of the input

Regular Expression Object Methods


Method Description
compile Change the regular expression (what to search for)
exec Search a string for a specified value. Returns the found value and remembers the
position
test Search a string for a specified value. Returns true or false
search Search a string for a specified value. Returns the position of the value
match Search a string for a specified value. Returns an array of the found value(s)
replace Replace characters with other characters
split Split a string into an array of strings

Building Rich Internet Applications with Adobe Flex 2-11


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

Example 1: The following example makes use of a regular expression object. Running the code
will replace the string “Dollar” with “Rupee”.

<HTML>
<script type="text/javascript">
var str = "A Dollar saved is a Dollar earned";
var search_string=new RegExp("Dollar");
var result = str.replace(search_string, "Rupee");
document.write(result);
</script>
</HTML>

2.6 Cascading Style Sheets(CSS)


2.6.1 Introduction to CSS
CSS stands for Cascading Style Sheets. CSS is an extension to basic HTML that allows you to
style your web pages. An example of a style change would be to make words italic. In standard
HTML you would use the <i> tag like so:

<i>Hello World</i>

There is nothing wrong in the above usage, but if you want to change all the italicized
paragraphs to bold, you would have to go to every paragraph in the document and change the
<i> tag to <b>.

Another disadvantage can be found in this example: say you wanted to make the above text
italic, make the font style Arial and change its color to blue; you would need a lot of code
wrapped around the text:

<font color="blue" face="Arial "><i>Hello World</i></font>

This is verbose and contributes to making you HTML messy. With CSS, you can create a custom
style elsewhere and set all its properties, give it a unique name and then ‘tag’ your HTML to
apply these stylistic properties:

<p class="myNewStyle">My CSS styled text</p>


And in between the <head></head> tags at the top of your web page you would insert this
CSS code that defines the style we just applied:

<style type="text/css">
<!--
.myNewStyle {
font-family: Arial;
font-style: italic;
color: #0000FF;
Building Rich Internet Applications with Adobe Flex 2-12
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

}
-->
</style>

In the above example the css code is directly embedded into the page itself. This is fine for
smaller projects or in situations where the styles being defined will only be used in a single
page. There are many times when the styles will be applied to many pages and it would be a
hassle to have to copy and paste your CSS code into each page.

Besides the fact that the pages will get cluttered with the same CSS code, you also find
yourself having to edit each of these pages if you want to make a style change. Like with
JavaScript, you can define/create your CSS styles in a separate file and then link it to the page
you want to apply the code to:

<link href="myStyleSheet.css" rel="stylesheet" type="text/css">

The above line of code links the external style sheet called ‘myStyleSheet.css’ to the HTML
document. Place this code in between the <head> </head> tags in your web page.

2.6.2 Creating a linked external CSS and other


examples
To create an external style sheet all you need to do is create a simple text document and then
change the file extension from type .txt to .css. CSS files are just specially formatted text files,
and much in the same way HTML pages are. There is nothing special or different in the file
itself, rather it is the contents of the file that make an HTML document and a CSS page what
they are.

When working with an external CSS document, there are a couple of points to remember:
1. You don’t add these tags in the CSS page itself as you would if you embedded the CSS code
in your HTML:
<style type="text/css">

</style>

Since the CSS link in your web page says that you are linking to a CSS page, you don’t need to
declare (in the external CSS file) that the code in the CSS page is CSS. That is what the above
tags do. Instead you would just add your CSS code directly to the page like so:

.style1 {
font-family: Arial;
font-style: italic;
color: #0000FF;
}
.style2 {
font-family: Verdana;
font-style: bold;

Building Rich Internet Applications with Adobe Flex 2-13


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

color: #00FF00;
}
.style3 {
font-family: Calibri;
font-style: italic;
color: #FF0000;
}
In the above example I have created a series CSS classes that can be applied to any HTML tag
like so:
<p class="style1">My CSS styled text comes here…</p>
Or
<h2 class=”style2”>My CSS styled text comes here…</h2>

You will notice that in the above example I applied a CSS style to a <h2> tag. Normally this tag
sets the size of the text that it wraps to a size that is preset in the browser (ex: 10 pixels).
When you apply a CSS class to it, the CSS code overrides the default size that you would
normally get with an <h2> tag in favor of the size specified in the CSS class. So now you can
see that CSS can override default HTML tag behavior!

In the above examples, I have CSS code where I define my CSS classes and then ‘apply’ them
to various elements in the page. Another way to apply CSS is to globally redefine an HTML tag
to look a certain way:

h1{ font-family: Garamond,"Times New Roman", serif; font-size: 200%; }

What this CSS code does is set the font style and size of all <h1> tags in one shot. Now you
don’t have to apply a CSS class as we did before to any <h1> tags since they are automatically
all affected by the CSS style rules.

Here is another example of where I give the whole page bigger margins.

body { margin-left: 15%; margin-right: 15%; }

As you can see, you can redefine any tag and change the way it looks! This can be very
powerful:
div {
background: rgb(204,204,255);
padding: 0.5em;
border: 1px solid #000000;
}
The above CSS code sets that any <div></div> tag will now have a background color of
‘rgb(204,204,255)’ and have a padding of 0.5em and a thin 1 pixel border that is solid black.
A few things to explain about the above:
Color in CSS can be expressed in a few ways:

• In Hex -> for example: #000000 – this is black and this: #FF0000 is red
• In rgb -> rgb(204,204,255) is a light purple blue color
• With named colors like: ‘red’ or ‘blue’

Building Rich Internet Applications with Adobe Flex 2-14


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

If you are not familiar/comfortable with hex color, you can write the last example as below:

div {
background: green;
padding: 0.5em;
border: 1px solid #FF0000;
}

So instead of ‘rgb(204,204,255)’ , I just specified ‘green’. By using RGB and Hex color, you can
really get the exact color you want easily when you know your codes. Luckily many tools (like
Dreamweaver) provide easy to use color pickers for you so you don’t need to know/remember
the values for the code.
In this last example I will show you the ‘super cool’ CSS code that allows you to create link roll-
over affects without images:

a:link { color: rgb(0, 0, 153) }


a:visited { color: rgb(153, 0, 153) }
a:hover { color: rgb(0, 96, 255) }
a:active { color: rgb(255, 0, 102) }

The above CSS will cause your links to change color when someone hovers their mouse pointer
over it, instant rollovers with no images! One important note with the above code, is that the
style declarations be in the right order: "link-visited-hover-active", otherwise it may break it in
some browsers.

CSS is very powerful and allows you to do things that you can’t do with standard HTML. It is
supported nicely now in all the modern browsers and is a must learn tool for web designers.
The above examples are just a small sample of what you can do with CSS, but it should be
more than enough for you to start styling your pages nicely.

2.7 Overview of XML


2.7.1 What is XML?
XML stands for eXtensible Markup Language. XML is used to store data or information. In XML,
data is "marked up" with tags, similar to HTML tags. This data might be intended to be by read
by people or by machines. It can be highly structured data such as data typically stored in
databases or spreadsheets, or loosely structured data, such as data stored in letters or
manuals.

2.7.2 Advantages of XML


Initially XML received a lot of excitement, which has now died down some. This is not because
XML is not as useful, but rather because it does not provide the glaze those other technologies,
such as HTML do. When you write an HTML document, you see a nicely formatted page in a

Building Rich Internet Applications with Adobe Flex 2-15


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

browser - instant gratification. When you write an XML document, you see an XML document -
not so exciting. However, with a little more effort, you can make that XML document glaze!
Some of the major benefits of XML are:

XML holds data - XML stores data in a structure way. Applications can then use this data to do
several things.

XML separates structure from formatting - One of the difficulties with HTML documents, word
processor documents (like WordStar, etc.) spreadsheets, and other forms of documents is that
they mix structure with formatting. This makes it difficult to manage content and design,
because the two are intermingled. As an example, in HTML, there is a <u> tag used for
underlining text. Very often, it is used for emphasis, but it also might be used to mark a book
title. It would be very difficult to write an application that searched through such a document
for book titles. In XML, the book titles could be placed in <book_title> tags and the emphasized
text could be place in <em> tags. The XML document does not specify how the content of
either tag should be displayed. Rather, the formatting is left up to an external stylesheet. Even
though the book titles and emphasized text might appear the same, it would be relatively
straight forward to write an application that finds all the book titles. It would simply look for
text in <book_title> tags. It also becomes much easier to reformat a document; for example, to
change all emphasized text to be italicized rather than underlined, but leave book titles
underlined.

XML promotes data sharing - Very often, applications that hold data in different structures must
share data with one another. It can be very difficult for a developer to map the different data
structures to each other. XML can serve as a go between. Each application's data structure is
mapped to an agreed-upon XML structure. Then all the applications share data in this XML
format. Each application only has to know two structures, its own and the XML structure, to be
able to share data with many other applications.

XML is Human-Readable - XML documents can be read by people. Perhaps this doesn't sound
so exciting, but compare it to data stored in a database. It is not easy to browse through a
database and read different segments of it as you would a text file.

XML is free - XML doesn't cost anything to use. It can be written with a simple text editor or
one of the many freely available XML authoring tools, such as XML Notepad. In addition, many
web development tools, such as Dreamweaver.

2.7.3 Uses of XML


• Configuration files (deployment descriptors) for servlets, EJBs
• Make files for Ant
• Content Management - Almost all of the leading content management systems use XML
in one way or another. A typical use would be to store a company's marketing content in
one or more XML documents. These XML documents could then be transformed for
output on the Web, as Word documents, as PowerPoint slides, in plain text, and even in
audio format. The content can also easily be shared with partners who can then output
the content in their own formats. Storing the content in XML makes it much easier to
Building Rich Internet Applications with Adobe Flex 2-16
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

manage content for two reasons. Content changes, additions, and deletions are made in
a central location and the changes will cascade out to all formats of presentation. There
is no need to be concerned about keeping the Word documents in sync with the
website, because the content itself is managed in one place and then transformed for
each output medium. Formatting changes are made in a central location. To illustrate,
suppose a company had many marketing web pages, all of which were produced from
XML content being transformed to HTML. The format for all of these pages could be
controlled from a single XSLT and a sitewide formatting change could be made
modifying that XSLT.
• Webservices -XML Web services are small applications or pieces of applications that are
made accessible on the Internet using open standards based on XML. Web services
generally consist of three components:SOAP - an XML-based protocol used to transfer
Web services over the Internet. WSDL (Web Services Description Language) - an XML-
based language for describing a Web service and how to call it. UDDI (Universal
Discovery Description and Integration) - the yellow pages of Web services. UDDI
directory entries are XML documents that describe the Web services a group offers. This
is how people find available Web services.
• RSS Feeds - RDF (Resource Description Framework) is a framework for writing XML-
based languages to describe information on the Web (e.g, web pages). RSS (RDF Site
Summary) is an implementation of this framework; it is a language that adheres to RDF
and is used to describe web content. Website publishers can use RSS to make content
available as a "feed", so that web users can access some of their content without
actually visiting their site. Often, RSS is used to provide summaries with links to the
company's website for additional information.

2.7.4 DTD
DTD stands for Document Type Declaration or DocType Declaration. The DTD has three roles.
It specifies the name of the document element
It may point to an external Document Type Definition (DTD)
It may contain an internal DTD.

The DOCTYPE Declaration shown below simply states that the document element of the XML
document is emp.
<!DOCTYPE emp>

If a DOCTYPE Declaration points to an external DTD, it must either specify that the DTD is on
the same system as the XML document itself or that it is in some public location. To do so, it
uses the keywords SYSTEM and PUBLIC. It then points to the location of the DTD using a
relative Uniform Resource Indicator (URI) or an absolute URI. Here are a couple of examples.
Syntax
<!--DTD is on the same system as the XML document-->
<!DOCTYPE emp SYSTEM "dtds/emp.dtd">

Syntax
<!--DTD is publicly available-->
<!DOCTYPE emp PUBLIC "-//r6i//DTD Emp 1.0//EN"

Building Rich Internet Applications with Adobe Flex 2-17


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

"http://www.r6i.com/emp/DTD/emp.dtd">

As shown in the second declaration above, public identifiers are divided into three parts:
• An organization (e.g, r6i)
• A name for the DTD (e.g, Emp 1.0)
• A language (e.g, EN for English)

Here is an example DTD (purchase.dtd) that defines the data type of purchase.xml document.

Purchase.dtd
<?xml version="1.0"?>
<!ELEMENT PURCHASEORDERS (PURCHASEORDER)*>
<!ELEMENT PURCHASEORDER
(PONO?,PODATE,VENDORNAME,EXPECTEDDD,POAMOUNT,LINEITEM+)>
<!ATTLIST PURCHASEORDER ZONE CDATA #REQUIRED CATEGORY (BOOKS | TOYS)
"TOYS" >
<!ELEMENT PONO (#PCDATA)>
<!ENTITY COPYRIGHT "2001 TELEPARADIGM">
<!ELEMENT PODATE (#PCDATA)>
<!ELEMENT VENDORNAME (#PCDATA)>
<!ELEMENT EXPECTEDDD (#PCDATA)>
<!ELEMENT POAMOUNT (#PCDATA)>
<!ELEMENT LINEITEM (ITEMNAME,ITEMCODE,QTY,ITEMPRICE)>
<!ELEMENT ITEMNAME (#PCDATA)>
<!ELEMENT ITEMCODE (#PCDATA)>
<!ELEMENT QTY (#PCDATA)>
<!ELEMENT ITEMPRICE (#PCDATA)>
Purchase.xml
<?xml version="1.0"?>
<!DOCTYPE PURCHASEORDERS SYSTEM "purchase.dtd">
<PURCHASEORDERS>
<PURCHASEORDER ZONE="SOUTH" CATEGORY="TOYS">
<PONO>8001</PONO>
<PODATE>12-JAN-2007 </PODATE>
<VENDORNAME>RMK &CO;</VENDORNAME>
<EXPECTEDDD>14-MAR-2008</EXPECTEDDD>
<POAMOUNT>12000</POAMOUNT>
<LINEITEM>
<ITEMNAME>COLGATE</ITEMNAME>
<ITEMCODE>1234</ITEMCODE>
<QTY>234</QTY>
<ITEMPRICE>2345</ITEMPRICE>
</LINEITEM>
</PURCHASEORDER>
</PURCHASEORDERS>

2.7.4.1 Limitations of DTD


• Content is limited to textual

Building Rich Internet Applications with Adobe Flex 2-18


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

• Difficult to put in repetition constraints


• DTD does not use XML syntax
• DTD does not say the following
 What the root element of the document is
 How many of instances of each kind of element appear in the document
 What the character data inside the elements looks like
 The semantic meaning of an element
 A DTD never says anything about the length, structure, meaning, allowed
values, or other aspects of the text content of an element

2.7.5 XML Schema


Motivations of XML Schema:
Provide more powerful and flexible schema language than DTD
Represent SML Document syntax in XML language (XML tools can be readily used)
Support non-textual data types
Handle complex syntax
Derived types, complex types can be defined

2.7.6 XML Schema Datatypes


Predefined Simple Types - String, CDATA, token, byte, unsignedByte, binary, integer,
positiveInteger, negativeInteger, nonNegativeInteger, nonPositiveInteger, int, unsignedInt,
long, unsignedLong, short, unsignedShort, decimal, float, double, boolean, time, timeInstant,
timePeriod, timeDuration, date, month, year, century, recurringDay, recurringDate,
recurringDuration, Name, Qname, NCName, uriReference, language, ID, IDREF, IDREFS,
ENTITY, ENTITIES, NOTATION, NMTOKEN, NMTOKENS.

Derived Simple Types - XML Schema supports derived simple types. The following are examples
of derived simple types.
Example 1 - Numeric Range
<xsd:simpleType name="myInteger">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="10000"/>
<xsd:maxInclusive value="99999"/>
</xsd:restriction>
</xsd:simpleType>

Example 2 - Regular Expression


<xsd:simpleType name="RMK">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{3}-[A-Z]{2}"/>
</xsd:restriction>
</xsd:simpleType>

Building Rich Internet Applications with Adobe Flex 2-19


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

Example 3 - Enumeration
<xsd:simpleType name="State">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="AP"/>
<xsd:enumeration value="MP"/>
<xsd:enumeration value="UP"/>
<!-- and so on ... -->
</xsd:restriction>
</xsd:simpleType>

Complex Types - Complex Types are defined using “complexType” element, complex type will
contain element declarations, element references, attribute declarations, etc.
Example:
<xsd:complexType name="PostalAddress" >
<xsd:sequence>
<xsd:element name="name" type="xsd:string" />
<xsd:element name="street" type="xsd:string" />
<xsd:element name="city" type="xsd:string" />
<xsd:element name="state" type="xsd:string" />
<xsd:element name="pin" type="xsd:decimal" />
</xsd:sequence>
<xsd:attribute name="country" type="xsd:NMTOKEN" use="fixed" value="INDIA"/>
</xsd:complexType

Here is an example XSD (blood_report.xsd) for blood_report.xml document.

blood_report.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="Blood_Report" type="Blood_ReportType"/>
<xsd:complexType name="Blood_ReportType">
<xsd:sequence>
<xsd:element name="PatientInfo" type="PatientInfoType"/>
<xsd:element name="BloodSampleInfo" type="BloodSampleInfoType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="PatientInfoType">
<xsd:sequence>
<xsd:element name="IdNo" type="xsd:integer"/>
<xsd:element name="pname" type="xsd:string"/>
<xsd:element name="Ref_Dr" type="xsd:string"/>
<xsd:element name="Date" type="xsd:date"/>
<xsd:element name="age" type="ageType"/>
<xsd:element name="state" type="stateType"/>
<xsd:element name="phone" type="phoneType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="phoneType">
<xsd:restriction base="xsd:integer">
Building Rich Internet Applications with Adobe Flex 2-20
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

<xsd:pattern value="\d{10}"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="ageType">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="1"/>
<xsd:maxInclusive value="99"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="stateType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="male"/>
<xsd:enumeration value="female"/>
<xsd:enumeration value="child"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:complexType name="BloodSampleInfoType">
<xsd:sequence>
<xsd:element name="Haemoglobin" type="xsd:integer"/>
<xsd:element name="RBC" type="xsd:decimal"/>
<xsd:element name="WBC" type="WBCType"/>
<xsd:element name="ESR" type="ESRType"/>
<xsd:element name="PCV" type="PCVType"/>
<xsd:element name="PlateletCount" type="PCType"/>
</xsd:sequence>
</xsd:complexType>

<xsd:complexType name="WBCType">
<xsd:sequence>
<xsd:element name="Neutrophils" type="xsd:integer"/>
<xsd:element name="Eosinophils" type="xsd:integer"/>
<xsd:element name="Lymphocytes" type="xsd:integer"/>
<xsd:element name="Monocytes" type="xsd:integer"/>
<xsd:element name="Basophils" type="xsd:decimal"/>
</xsd:sequence>
</xsd:complexType>

<xsd:simpleType name="ESRType">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="0"/>
<xsd:maxInclusive value="15"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name="PCVType">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="36"/>
Building Rich Internet Applications with Adobe Flex 2-21
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

<xsd:maxInclusive value="54"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name="PCType">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="150000"/>
<xsd:maxInclusive value="450000"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>

blood_report.xml
<?xml version="1.0"?>
<Blood_Report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation='blood_report.xsd'>
<PatientInfo>
<IdNo>342</IdNo>
<pname>DeepakLalwani</pname>
<Ref_Dr>Dr. Rayapudi MuraliKrishna</Ref_Dr>
<Date>2005-07-22</Date>
<age>24</age>
<state>male</state>
<phone>9440411033</phone>
</PatientInfo>
<BloodSampleInfo>
<Haemoglobin>15</Haemoglobin>
<RBC>5.0</RBC>
<WBC>
<Neutrophils>50</Neutrophils>
<Eosinophils>3</Eosinophils>

<Lymphocytes>30</Lymphocytes>
<Monocytes>5</Monocytes>
<Basophils>0.4</Basophils>
</WBC>
<ESR>12</ESR>
<PCV>44</PCV>
<PlateletCount>250000</PlateletCount>
</BloodSampleInfo>
</Blood_Report>

Building Rich Internet Applications with Adobe Flex 2-22


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

2.7.7 XSLT
XSLT stands for eXtensible Stylesheet Language Transformation. XSLT transforms XML
document into another XML, XHTML, WML, HTML or Text. XSLT is used in the two following
areas:
Presentation Oriented Publishing (POP) e.g. Browsers and Editors
Message Oriented Middleware (MOM) e.g. Machine-to-Machine data exchange

2.7.7.1 XSLT in Presentation Oriented Publishing


We know that XML document separates content from presentation. Transformations can be
used to style XML documents; a common styling technique presents XML in HTML format. XSLT
Processor (XSLT processor is built-in almost all recent browsers, web-servers and application
servers) is a program that reads an XSLT style sheet and input XML document and then
converts the input document into an output document according to the instructions given in the
stylesheet. The following diagram shows how the XML document is rendered to HTML
document.

Figure 2.7.7.1a XSLT in Message Oriented Middleware

XSLT in Message Oriented Middleware is important for ecommerce, B2B, and dynamic content
generation.

Building Rich Internet Applications with Adobe Flex 2-23


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

Figure 2.7.7.1b XSLT Stylesheet Language constructs

XSLT Stylesheet is nothing but an XML document. The root element is either stylesheet or
transform, both are defined in standard XSLT namespace http://www.w3.org/XSL/Transform.
Stylesheet language uses several constructs in order to process the XML documents according
to the requirements. The following section explains the language constructs.

People.xml
<?xml version="1.0"?>
<people>
<person born="1879" died="1955">
<name>
<first_name>Albert</first_name>
<last_name>Einstein</last_name>
</name>
<profession>Physicist</profession>
<profession>mathematician</profession>
<profession>Teacher</profession>
</person>
<person born="1642" died="1679">
<name>
<first_name>Sir</first_name>
<middle_initial>Isaac</middle_initial>
<last_name>Newton</last_name>
</name>
<profession>Scientist</profession>
<hobby>Playing the bongoes</hobby>
</person>
</people>
Building Rich Internet Applications with Adobe Flex 2-24
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

2.7.7.2 Templates
Templates control which output is created from which input. Template syntax
< xsl:template> </xsl:template>. The “match” attribute contains an Xpath expression, where
as Xpath expression identifies input node set it matches.

For each node in the node set, the template contents (things between xsl:template tags) are
instantiated are inserted into the output tree.
Example

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match=”people">
</xsl:template>
</xsl:stylesheet>

2.7.7.3 xsl:value-of
xsl:value-of element extracts the string value of an element or an attribute and writes it to
output, select attribute containing XPath expression identifies an element or an attribute, if it is
a node set, in which case, the string value of node is taken.
Example

<?xml version="1.0"?>
<xsl:stylesheet version="1.0”
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="person">
<p>
<xsl:value-of select="name"/>
</p>
</xsl:template>
</xsl:stylesheet>

If we apply this style sheet on People.xml document, it will print the below output:
<p>
Albert
Einstein
</p>
<p>
Sir
Isaac
Newton
</p>

Building Rich Internet Applications with Adobe Flex 2-25


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

2.7.7.4 xsl:apply-templates
Usually as the XSLT processor reads (traverses) the input XML document sequentially from top
to bottom, templates are activated in the order they match elements encountered, template for
a parent will be activated before the children. The order of the traversal can be changed by
apply-templates.

• It can specify which element or elements should be processed next


• It can specify an element or elements should be processed in the middle of processing
element
• It can prevent particular elements from being processed
• Xsl:apply-templates lets you make your choice of processing order explicit.

The select attribute contains XPath expression telling the XSLT processor which nodes to
process in the input tree. The apply-template with no select attribute means all elements
relative to the current element should be matched.
Example

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="person">
<xsl:apply-templates select="name"/>
</xsl:template>
<xsl:template match="name">
<xsl:value-of select="last_name"/>,
<xsl:value-of select="first_name"/>
</xsl:template>
</xsl:stylesheet>

If we apply this style sheet on People.xml document, it will print the below output:

Einstein
Albert
Newton
Sir

2.7.7.5 xsl:for-each
xsl:for-each iterates through a node set.

Example
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="people">
<xsl:for-each select="person">
<xsl:value-of select="name"/>
Building Rich Internet Applications with Adobe Flex 2-26
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

<xsl:value-of select="@born"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

If we apply this style sheet on People.xml document, it will print the below output:

Albert
Einstein
1879

Sir
Isaac
Newton
1642

2.7.7.6 xsl:if
Using xsl:if we can check content for certain values. In order to test the content the “test”
attribute is required and it will either be true or false.
Syntax: <xsl:if test=criteria></xsl:if>

Example
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
bxmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="people">
<xsl:for-each select="person">
<xsl:value-of select="name"/>
<xsl:if test="@born=’1879’">
Died in
<xsl:value-of select="@died"/>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

If we apply this style sheet on People.xml document, it will print the below output:

Albert
Einstein
Died in
1955
Sir
Isaac
Newton

2.7.7.7 xsl:choose
Building Rich Internet Applications with Adobe Flex 2-27
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

Using xsl:choose also we can select content. The “test” attribute works in the same fashion as
in xsl:if.
Example
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="people">
<xsl:for-each select="person">
<xsl:value-of select="name"/>
<xsl:choose>
<xsl:when test="@born='1879'">
Died in <xsl:value-of select="@died"/>
</xsl:when>
<xsl:otherwise>
Did not die in 1955
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

If we apply this style sheet on People.xml document, it will print the below output:

Albert Einstein
Died in 1955
Sir Isaac Newton
Did not die in 1955

2.7.7.8 xsl:sort
XSLT provides a nice way to sort documents by elements contents.

Syntax: <xsl:sort select=selection></xsl:sort>

Example (This example sorts data by name in default order (ascending order))

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="people">
<xsl:apply-templates>
<xsl:sort select="name"/>
</xsl:apply-templates>
</xsl:template>
</xsl:stylesheet>

If we apply this style sheet on People.xml document, it will print the below output:

Albert
Building Rich Internet Applications with Adobe Flex 2-28
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

Einstein

Physicist
Mathematician
Teacher

Sir
Isaac
Newton

Scientist
Playing the bongos

Example (This example sorts data by name in descending order)

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="people">
<xsl:apply-templates>
<xsl:sort select="name" order=”descending”/>
</xsl:apply-templates>
</xsl:template>
</xsl:stylesheet>

If we apply this style sheet on People.xml document, it will print the below output:

Sir
Isaac
Newton

Scientist
Playing the bongoes

Albert
Einstein

Physicist
Mathematician
Teacher

2.7.8 SAX Parser


Simple API for XML (SAX) is an event-driven, serial-access mechanism for accessing XML
documents. This protocol is frequently used by servlets and network-oriented programs that
need to transmit and receive XML documents, because it's the fastest and least memory-
intensive mechanism that is currently available for dealing with XML documents, other than
StAX.

Building Rich Internet Applications with Adobe Flex 2-29


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

In a nutshell, SAX is oriented towards state independent processing, where the handling of an
element does not depend on the elements that came before. StAX, on the other hand, is
oriented towards state dependent processing.

Setting up a program to use SAX requires a bit more work than setting up to use the Document
Object Model (DOM) (DOM is another parser, we will discuss DOM in next section). SAX is an
event-driven model (you provide the callback methods, and the parser invokes them as it reads
the XML data), and that makes it harder to visualize. Finally, you can't "back up" to an earlier
part of the document, or rearrange it, any more than you can back up a serial data stream or
rearrange characters you have read from that stream.

For those reasons, developers who are writing a user-oriented application that displays an XML
document and possibly modifies it will want to use the DOM mechanism. However, even if you
plan to build DOM applications exclusively, there are several important reasons for familiarizing
yourself with the SAX model:

Same Error Handling: The same kinds of exceptions are generated by the SAX and DOM APIs,
so the error handling code is virtually identical.
Handling Validation Errors: By default, the specifications require that validation errors are
ignored. If you want to throw an exception in the event of a validation error (and you probably
do), then you need to understand how SAX error handling works.
Converting Existing Data: There is a mechanism you can use to convert an existing data set to
XML. However, taking advantage of that mechanism requires an understanding of the SAX
model.

When to Use SAX?

It is helpful to understand the SAX event model when you want to convert existing data to XML.
As you'll see in Generating XML from an Arbitrary Data Structure, the key to the conversion
process is to modify an existing application to deliver SAX events as it reads the data.
SAX is fast and efficient, but its event model makes it most useful for such state-independent
filtering. For example, a SAX parser calls one method in your application when an element tag is
encountered and calls a different method when text is found. If the processing you're doing is
state-independent (meaning that it does not depend on the elements have come before), then
SAX works fine.

On the other hand, for state-dependent processing, where the program needs to do one thing
with the data under element A but something different with the data under element B, then a
pull parser such as the Streaming API for XML (StAX) would be a better choice. With a pull
parser, you get the next node, whatever it happens to be, at any point in the code that you ask
for it. So it's easy to vary the way you process text (for example), because you can process it
multiple places in the program.

SAX requires much less memory than DOM, because SAX does not construct an internal
representation (tree structure) of the XML data, as a DOM does. Instead, SAX simply sends data
to the application as it is read; your application can then do whatever it wants to do with the
data it sees.

Building Rich Internet Applications with Adobe Flex 2-30


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

Pull parsers and the SAX API both act like a serial I/O stream. You see the data as it streams in,
but you can't go back to an earlier position or leap ahead to a different position. In general,
such parsers work well when you simply want to read data and have the application act on it.
But when you need to modify an XML structure--especially when you need to modify it
interactively--an in-memory structure makes more sense. DOM is one such model. However,
although DOM provides many powerful capabilities for large-scale documents (like books and
articles), it also requires a lot of complex coding. The details of that process are highlighted in
When to Use DOM.
Example
The following java program parses the cdcatalg.xml and stores the data in a Oracle table.
Cdcatalog.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="C:\Documents and
Settings\genesis\Desktop\test.xsl"?>
<catalog>
<cd media="dvd">
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd media="cd">
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
<cd media="cd">
<title>Greatest Hits</title>
<artist>Dolly Parton</artist>
<country>USA</country>
<company>RCA</company>
<price>9.90</price>
<year>1982</year>
</cd>
<cd media="dvd">
<title>Still got the blues</title>
<artist>Gary Moore</artist>
<country>UK</country>
<company>Virgin records</company>
<price>10.20</price>
<year>1990</year>
</cd>
<cd media="cd">
<title>Eros</title>
<artist>Eros Ramazzotti</artist>

Building Rich Internet Applications with Adobe Flex 2-31


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

<country>EU</country>
<company>BMG</company>
<price>9.90</price>
<year>1997</year>
</cd>
<cd media="dvd">
<title>One night only</title>
<artist>Bee Gees</artist>
<country>UK</country>
<company>Polydor</company>
<price>10.90</price>
<year>1998</year>
</cd>
<cd media="cd">
<title>Sylvias Mother</title>
<artist>Dr.Hook</artist>
<country>UK</country>
<company>CBS</company>
<price>8.10</price>
<year>1973</year>
</cd>
<cd media="cd">
<title>Maggie May</title>
<artist>Rod Stewart</artist>
<country>UK</country>
<company>Pickwick</company>
<price>8.50</price>
<year>1990</year>
</cd>
<cd media="dvd">
<title>Romanza</title>
<artist>Andrea Bocelli</artist>
<country>EU</country>
<company>Polydor</company>
<price>10.80</price>
<year>1996</year>
</cd>
<cd media="cd">
<title>When a man loves a woman</title>
<artist>Percy Sledge</artist>
<country>USA</country>
<company>Atlantic</company>
<price>8.70</price>
<year>1987</year>
</cd>
<cd media="cd">
<title>Black angel</title>
<artist>Savage Rose</artist>
<country>EU</country>
<company>Mega</company>
<price>10.90</price>
Building Rich Internet Applications with Adobe Flex 2-32
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

<year>1995</year>
</cd>
<cd media="dvd">
<title>1999 Grammy Nominees</title>
<artist>Many</artist>
<country>USA</country>
<company>Grammy</company>
<price>10.20</price>
<year>1999</year>
</cd>
<cd media="cd">
<title>For the good times</title>
<artist>Kenny Rogers</artist>
<country>UK</country>
<company>Mucik Master</company>
<price>8.70</price>
<year>1995</year>
</cd>
<cd media="dvd">
<title>Big Willie style</title>
<artist>Will Smith</artist>
<country>USA</country>
<company>Columbia</company>
<price>9.90</price>
<year>1997</year>
</cd>
<cd media="cd">
<title>Tupelo Honey</title>
<artist>Van Morrison</artist>
<country>UK</country>
<company>Polydor</company>
<price>8.20</price>
<year>1971</year>
</cd>
<cd media="dvd">
<title>Soulsville</title>
<artist>Jorn Hoel</artist>
<country>Norway</country>
<company>WEA</company>
<price>7.90</price>
<year>1996</year>
</cd>
<cd media="cd">
<title>The very best of</title>
<artist>Cat Stevens</artist>
<country>UK</country>
<company>Island</company>
<price>8.90</price>
<year>1990</year>
</cd>
<cd media="cd">
Building Rich Internet Applications with Adobe Flex 2-33
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

<title>Stop</title>
<artist>Sam Brown</artist>
<country>UK</country>
<company>A and M</company>
<price>8.90</price>
<year>1988</year>
</cd>
<cd media="dvd">
<title>Bridge of Spies</title>
<artist>T`Pau</artist>
<country>UK</country>
<company>Siren</company>
<price>7.90</price>
<year>1987</year>
</cd>
<cd media="cd">
<title>Private Dancer</title>
<artist>Tina Turner</artist>
<country>UK</country>
<company>Capitol</company>
<price>8.90</price>
<year>1983</year>
</cd>
<cd media="cd">
<title>Midt om natten</title>
<artist>Kim Larsen</artist>
<country>EU</country>
<company>Medley</company>
<price>7.80</price>
<year>1983</year>
</cd>
<cd media="dvd">
<title>Pavarotti Gala Concert</title>
<artist>Luciano Pavarotti</artist>
<country>UK</country>
<company>DECCA</company>
<price>9.90</price>
<year>1991</year>
</cd>
<cd media="cd">
<title>The dock of the bay</title>
<artist>Otis Redding</artist>
<country>USA</country>
<company>Atlantic</company>
<price>7.90</price>
<year>1987</year>
</cd>
<cd media="cd">
<title>Picture book</title>
<artist>Simply Red</artist>
<country>EU</country>
Building Rich Internet Applications with Adobe Flex 2-34
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

<company>Elektra</company>
<price>7.20</price>
<year>1985</year>
</cd>
<cd media="dvd">
<title>Red</title>
<artist>The Communards</artist>
<country>UK</country>
<company>London</company>
<price>7.80</price>
<year>1987</year>
</cd>
<cd media="cd">
<title>Unchain my heart</title>
<artist>Joe Cocker</artist>
<country>USA</country>
<company>EMI</company>
<price>8.20</price>
<year>1987</year>
</cd>
</catalog>

Cdcatalog.java
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.*;
import java.sql.*;
import java.util.*;
import java.io.*;
public class CdCatalog extends DefaultHandler{
Statement stmt;
Connection con;
int flag=0;
String insertstring;
public static void main(String[] args){
if(args.length!=1){
System.out.println("usage:cmd filename");
System.exit(1);
}else{
try{
SAXParserFactory
factory=SAXParserFactory.newInstance();
SAXParser saxparser=factory.newSAXParser();
saxparser.parse(new File(args[0]),new
CdCatalog());
}catch(Exception e){
e.getMessage();
}
}
}
public void startDocument() throws SAXException {
Building Rich Internet Applications with Adobe Flex 2-35
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

try{
Class.forName("oracle.jdbc.driver.OracleDriver");

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521
:orcl","scott","tiger");
stmt=con.createStatement();
}catch(Exception e4){
e4.getMessage();
}
}
public void endDocument()throws SAXException{
try{
con.close();
}catch(Exception e2)
{
e2.getMessage();
}
}
public void startElement(String uri,String localName,String
qName,Attributes attributes)throws SAXException{
if(qName.equals("title")){
System.out.println("title");
flag=1;
}else if(qName.equals("artist")){
System.out.println("artist");
flag=2;
}else if(qName.equals("country")){
System.out.println("country");
flag=3;
}else if(qName.equals("company")){
System.out.println("company");
flag=4;
}else if(qName.equals("price")){
System.out.println("price");
flag=5;
}else if(qName.equals("year")){
System.out.println("year");
flag=6;
}
}
public void characters(char[] ch,int start,int length)throws
SAXException{
String str=new String(ch,start,length);
if(flag==1){
insertstring="'"+str+"',";
flag=0;
}else if(flag==2){
insertstring=insertstring+"'"+str+"',";
flag=0;
}else if(flag==3){
insertstring=insertstring+"'"+str+"',";
Building Rich Internet Applications with Adobe Flex 2-36
_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

flag=0;
}else if(flag==4){
insertstring=insertstring+"'"+str+"',";
flag=0;
}else if(flag==5){
insertstring=insertstring+"'"+str+"',";
flag=0;
}else if(flag==6){
try{
insertstring=insertstring+"'"+str+"'";
String s="insert into catalogsax
values("+insertstring+")";
System.out.println("------------------->"+s);
stmt.executeUpdate(s);
insertstring="";
flag=0;
}catch(Exception e1){
e1.getMessage();
}
}
}
}

2.7.9 DOM Parser


DOM is a standard defined by the W3C, just like XML, DOM was not designed specifically for
Java technology (unlike SAX), DOM is cross-platform and cross-language.

DOM Characteristics
DOM Access XML document as a tree structure composed of mostly element nodes and text
nodes. We can walk the DOM tree back and forth.

DOM Tree and Nodes


In DOM XML document is represented as a tree, a tree is made of nodes, there are 12 different
node types, and nodes may contain other nodes.
• Node Types
• Document node
• Document Fragment node
• Element node
• Attribute node
• Text node
• Comment node
• Processing instruction node
• Document type node
• Entity node
• Entity reference node
• CDATA section node
• Notation node

Building Rich Internet Applications with Adobe Flex 2-37


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

DOM Tree Hierarchy


A document node contains one element node (root element node) and one or more processing
instruction nodes. An element node may contain other element nodes, one or more text nodes
and one or more attribute nodes. An attribute node contains a text node.
E.g. the following java program uses DOM parser to enhance the price of each CD element of
cdcatalg.xml (refer previous section) and stores in new xml file named out.xml.

PriceEnhancer.java
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.*;
class PriceEnhancer{
public static void main(String[] args){
try{
DocumentBuilderFactory
dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse(new File(args[0]));
NodeList pnl=doc.getElementsByTagName("price");
for(int i=0;i<pnl.getLength();i++){
Node pn=pnl.item(i);
Node cn=pn.getFirstChild();
String s=(String)cn.getNodeValue();
float f=Float.parseFloat(s);
f=f+5;
Text t=doc.createTextNode(f+"");
pn.replaceChild(t,cn);
}
TransformerFactory tf=TransformerFactory.newInstance();
Transformer t1=tf.newTransformer();
Source input=new DOMSource(doc);
Result output=new StreamResult(new
FileOutputStream("out.xml"));
t1.transform(input,output);
}catch (Exception e){
e.printStackTrace();
}
}
}

Building Rich Internet Applications with Adobe Flex 2-38


_______________________________________________________________________
Lesson 2: Programming web clients
_____________________________________________________________________________

2.8 Summary
• Technologies used to build client side applications include JavaScript, CSS and XML.
JavaScript is a lightweight programming language with many useful features.

• XML stands for eXtensible Markup Language. XML is used to store data or information.
In XML, data is "marked up" with tags, similar to HTML tags. XML is used for multiple
purposes including configuration files, make files for the ANT tool, content management,
web services and RSS feeds.

• An XML document separates content from presentation. Transformations can be used


to style XML documents. XSLT is a common styling technique that presents XML in
HTML format. An XSLT Processor is a program that reads an XSLT style sheet and input
XML document and then converts the input document into an output document
according to the instructions given in the stylesheet.

• Simple API for XML (SAX) is an event-driven, serial-access mechanism for accessing XML
documents. DOM is a standard defined by the W3C, just like XML. Unlike SAX DOM was
not designed specifically for Java technology, DOM is cross-platform and cross-language.

Building Rich Internet Applications with Adobe Flex 2-39


_______________________________________________________________________

You might also like