0% found this document useful (0 votes)
57 views

XML Unit 3

Uploaded by

Tammaneni Navya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

XML Unit 3

Uploaded by

Tammaneni Navya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

XML

XML stands for Extensible Markup Language. It is a text-based markup language derived
from Standard Generalized Markup Language (SGML).

XML tags identify the data and are used to store and organize the data, rather than
specifying how to display it like HTML tags, which are used to display the data. XML is
not going to replace HTML in the near future, but it introduces new possibilities by
adopting many successful features of HTML.

There are three important characteristics of XML that make it useful in a variety of
systems and solutions:

 XML is extensible: XML allows you to create your own self-descriptive tags or
language, that suits your application.

 XML carries the data, does not present it: XML allows you to store the data
irrespective of how it will be presented.

 XML is a public standard: XML was developed by an organization called the
World Wide Web Consortium (W3C) and is available as an open standard.

XML Usage
A short list of XML usage says it all:


 XML can be used to exchange the information between organizations and systems.

 XML can be used for offloading and reloading of databases.

 XML can be used to store and arrange the data, which can customize your data
handling needs.

 XML can easily be merged with style sheets to create almost any desired output.

 Virtually, any type of data can be expressed as an XML document.
XML

What is Markup?
XML is a markup language that defines set of rules for encoding documents in a format
that is both human-readable and machine-readable. So, what exactly is a markup
language? Markup is information added to a document that enhances its meaning in
certain ways, in that it identifies the parts and how they relate to each other. More
specifically, a markup language is a set of symbols that can be placed in the text of a
document to demarcate and label the parts of that document.

Following example shows how XML markup looks, when embedded in a piece of text:

<message>
<text>Hello, world!</text>
</message>

This snippet includes the markup symbols, or the tags such as <message>...</message>
and <text>... </text>. The tags <message> and </message> mark the start and the end of
the XML code fragment. The tags <text> and </text> surround the text Hello, world!.

Is XML a Programming Language?


A programming language consists of grammar rules and its own vocabulary which is
used to create computer programs. These programs instruct the computer to perform
specific tasks. XML does not qualify to be a programming language as it does not
perform any computation or algorithms. It is usually stored in a simple text file and is
processed by special software that is capable of interpreting XML.

simple syntax rules to write an XML document.


Following is a complete XML document:

<?xml version="1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>AbcTechnologies</company>
<phone>(011) 123-4567</phone>
</contact-info>

You can notice, there are two kinds of information in the above example:

 Markup, like <contact-info>



 The text, or the character data, AbcTechnologies and (040) 123-4567
The following diagram depicts the syntax rules to write different types of markup and
text in an XML document.

Let us see each component of the above diagram in detail.


XML

XML Declaration
The XML document can optionally have an XML declaration. It is written as follows:

<?xml version="1.0" encoding="UTF-8"?>

Where version is the XML version and encoding specifies the character encoding used in
the document.

Syntax Rules for XML Declaration


 The XML declaration is case sensitive and must begin with "<?xml>" where
"xml" is written in lower-case.

 If the document contains XML declaration, then it strictly needs to be the first
statement of the XML document.

 The XML declaration strictly needs be the first statement in the XML document.

 An HTTP protocol can override the value of encoding that you put in the XML
declaration.

Tags and Elements


An XML file is structured by several XML-elements, also called XML-nodes or XML-tags.
The names of XML-elements are enclosed in triangular brackets < > as shown below:

<element>

Syntax Rules for Tags and Elements


Element Syntax: Each XML-element needs to be closed either with start or with end
elements as shown below:

<element>....</element>

or in simple-cases, just this way:

<element/>

Nesting of Elements: An XML-element can contain multiple XML-elements as its


children, but the children elements must not overlap. i.e., an end tag of an element
must have the same name as that of the most recent unmatched start tag.
XML

The following example shows incorrect nested tags:

<?xml version="1.0"?>
<contact-info>
<company>AbcTechnologies
<contact-info>
</company>

The following example shows correct nested tags:

<?xml version="1.0"?>
<contact-info>
<company>AbcTechnologies</company>
<contact-info>

Root Element: An XML document can have only one root element. For example,
following is not a correct XML document, because both the x and y elements occur at the
top level without a root element:

<x>...</x>
<y>...</y>

The following example shows a correctly formed XML document:

<root>
<x>...</x>
<y>...</y>
</root>

Case Sensitivity: The names of XML-elements are case-sensitive. That means the
name of the start and the end elements need to be exactly in the same case.

For example, <contact-info> is different from <Contact-Info>.

XML Attributes
An attribute specifies a single property for the element, using a name/value pair. An
XML-element can have one or more attributes. For example:

<a href="http://www.AbcTechnologies.com/">AbcTechnologies!</a>

Here href is the attribute name and http://www.AbcTechnologies.com/ is attribute


value.

Syntax Rules for XML Attributes

 Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href
are considered two different XML attributes.
XML

 Same attribute cannot have two values in a syntax. The following example shows
incorrect syntax because the attribute b is specified twice:

<a b="x" c="y" b="z">....</a>

 Attribute names are defined without quotation marks, whereas attribute values
must always appear in quotation marks. Following example demonstrates
incorrect xml syntax:

<a b=x>....</a>

In the above syntax, the attribute value is not defined in quotation marks.

XML declaration

It contains details that prepare an XML processor to parse the XML document. It is
optional, but when used, it must appear in the first line of the XML document.

Syntax
Following syntax shows XML declaration:

<?xml
version="version_number"
encoding="encoding_declaration"
standalone="standalone_status"
?>

Each parameter consists of a parameter name, an equals sign (=), and parameter value
inside a quote. Following table shows the above syntax in detail:

Parameter Parameter_value Parameter_description

Specifies the version of the XML standard


Version 1.0
used.

UTF-8, UTF-16, ISO-

10646-UCS-2, ISO-

10646-UCS-4, ISO- It defines the character encoding used in


Encoding the document. UTF-8 is the default
8859-1 to ISO-8859-9,
encoding used.
ISO-2022-JP, Shift_JIS,

EUC-JP

It informs the parser whether the


document relies on the information from
an external source, such as external
Standalone yes or no. document type definition (DTD), for its
content. The default value is set to no.
Setting it to yes tells the processor there
are no external declarations required for
parsing the document.
XML Declaration Examples
Following are few examples of XML declarations:

XML declaration with no parameters:

<?xml >

XML declaration with version definition:

<?xml version="1.0">

XML declaration with all parameters defined:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>

XML declaration with all parameters defined in single quotes:

<?xml version='1.0' encoding='iso-8859-1' standalone='no' ?>

XML Tags Rules


Following are the rules that need to be followed to use XML tags:

Rule 1
XML tags are case-sensitive. Following line of code is an example of wrong syntax
</Address>, because of the case difference in two tags, which is treated as erroneous
syntax in XML.

<address>This is wrong syntax</Address>

Following code shows a correct way, where we use the same case to name the start and
the end tag.

<address>This is correct syntax</address>

Rule 2
XML tags must be closed in an appropriate order, i.e., an XML tag opened inside another
element must be closed before the outer element is closed. For example:

<outer_element>
<internal_element>
This tag is closed before the outer_element
</internal_element>
</outer_element>
Document Type Declaration(DTD)

The XML Document Type Declaration, commonly known as DTD, is a way to describe
XML language precisely. DTDs check vocabulary and validity of the structure of XML
documents against grammatical rules of appropriate XML language.

An XML DTD can be either specified inside the document, or it can be kept in a separate
document and then liked separately.

Syntax
Basic syntax of a DTD is as follows:

<!DOCTYPE element DTD identifier


[
declaration1
declaration2
........
]>

In the above syntax,

 The DTD starts with <!DOCTYPE delimiter.



 An element tells the parser to parse the document from the specified root
element.

 DTD identifier is an identifier for the document type definition, which may be
the path to a file on the system or URL to a file on the internet. If the DTD is
pointing to external path, it is called External Subset.

 The square brackets [ ] enclose an optional list of entity declarations called
Internal Subset.

Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML files. To
refer it as internal DTD, standalone attribute in XML declaration must be set to yes. This
means, the declaration works independent of an external source.
XML

Syntax
Following is the syntax of internal DTD:

<!DOCTYPE root-element [element-declarations]>

where root-element is the name of root element and element-declarations is where you
declare the elements.

Example
Following is a simple example of internal DTD:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>


<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Tanmay Patil</name>
<company>AbcTechnologies</company>
<phone>(011) 123-4567</phone>
</address>

Let us go through the above code:

Start Declaration - Begin the XML declaration with the following statement.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

DTD - Immediately after the XML header, the document type declaration follows,
commonly referred to as the DOCTYPE:

<!DOCTYPE address [

The DOCTYPE declaration has an exclamation mark (!) at the start of the element name.
The DOCTYPE informs the parser that a DTD is associated with this XML document.

DTD Body - The DOCTYPE declaration is followed by the body of the DTD, where you
declare elements, attributes, entities, and notations.

<!ELEMENT address (name,company,phone)>


<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone_no (#PCDATA)>
XML

Several elements are declared here that make up the vocabulary of the <name>
document. <!ELEMENT name (#PCDATA)> defines the element name to be of type
"#PCDATA". Here, #PCDATA means parse-able text data.

End Declaration - Finally, the declaration section of the DTD is closed using a closing
bracket and a closing angle bracket (]>). This effectively ends the definition, and
thereafter, the XML document follows immediately.

Rules
 The document type declaration must appear at the start of the document (preceded
only by the XML header) — it is not permitted anywhere else within the document.

 Similar to the DOCTYPE declaration, the element declarations must start with an
exclamation mark.

 The Name in the document type declaration must match the element type of the
root element.

External DTD
In external DTD elements are declared outside the XML file. They are accessed by
specifying the system attributes which may be either the legal .dtd file or a valid URL. To
refer it as external DTD, standalone attribute in the XML declaration must be set as no.
This means, declaration includes information from the external source.

Syntax
Following is the syntax for external DTD:

<!DOCTYPE root-element SYSTEM "file-name">

where file-name is the file with .dtd extension.

Example
The following example shows external DTD usage:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>


<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Tanmay Patil</name>
<company>AbcTechnologies</company>
<phone>(011) 123-4567</phone>
</address>
XML

The content of the DTD file address.dtd is as shown:

<!ELEMENT address (name,company,phone)>


<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>

Types
You can refer to an external DTD by using either system identifiers or public
identifiers.

System Identifiers
A system identifier enables you to specify the location of an external file containing DTD
declarations. Syntax is as follows:

<!DOCTYPE name SYSTEM "address.dtd" [...]>

As you can see, it contains keyword SYSTEM and a URI reference pointing to the location
of the document.

Public Identifiers
Public identifiers provide a mechanism to locate DTD resources and is written as follows:

<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">

As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public
identifiers are used to identify an entry in a catalog. Public identifiers can follow any format,
however, a commonly used format is called Formal Public Identifiers, or FPIs.

DTD - XML Building Blocks

Seen from a DTD point of view, all XML documents are made up by the following building
blocks:

 Elements
 Attributes
 Entities
 PCDATA
 CDATA

Elements
Elements are the main building blocks of both XML and HTML documents.

Examples of HTML elements are "body" and "table". Examples of XML elements could be
"note" and "message". Elements can contain text, other elements, or be empty.
Examples of empty HTML elements are "hr", "br" and "img".
Examples:

<body>some text</body>

<message>some text</message>

Attributes
Attributes provide extra information about elements.

Attributes are always placed inside the opening tag of an element. Attributes always
come in name/value pairs. The following "img" element has additional information about
a source file:

<img src="computer.gif" />

The name of the element is "img". The name of the attribute is "src". The value of the
attribute is "computer.gif". Since the element itself is empty it is closed by a " /".

Entities
Some characters have a special meaning in XML, like the less than sign (<) that defines
the start of an XML tag.

Most of you know the HTML entity: "&nbsp;". This "no-breaking-space" entity is used in
HTML to insert an extra space in a document. Entities are expanded when a document is
parsed by an XML parser.

The following entities are predefined in XML:

Entity References Character

&lt; <

&gt; >
&amp; &

&quot; "

&apos; '

PCDATA
PCDATA means parsed character data.

Think of character data as the text found between the start tag and the end tag of an
XML element.

PCDATA is text that WILL be parsed by a parser. The text will be examined by
the parser for entities and markup.

Tags inside the text will be treated as markup and entities will be expanded.

However, parsed character data should not contain any &, <, or > characters; these
need to be represented by the &amp; &lt; and &gt; entities, respectively.

CDATA
CDATA means character data.

CDATA is text that will NOT be parsed by a parser. Tags inside the text will NOT be
treated as markup and entities will not be expanded.

Validation is a process by which an XML document is validated. An XML document is


said to be valid if its contents match with the elements, attributes, and associated
document type declaration (DTD), and if the document complies with the constraints
expressed in it. Validation is dealt in two ways by the XML parser. They are:

 Well-formed XML document



 Valid XML document
Well-formed XML Document
An XML document is said to be well-formed if it adheres to the following rules:

 Non DTD XML files must use the predefined character entities for amp(&),
apos(single quote), gt(>), lt(<), quot(double quote).

 It must follow the ordering of the tag. i.e., the inner tag must be closed before
closing the outer tag.

 Each of its opening tags must have a closing tag or it must be a self-ending tag
(<title>....</title> or <title/>).

 It must have only one attribute in a start tag, which needs to be quoted.

 amp(&), apos(single quote), gt(>), lt(<), quot(double quote) entities
other than these must be declared.

Example
Following is an example of a well-formed XML document:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>


<!DOCTYPE address
[
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Tanmay Patil</name>
<company>AbcTechnologies</company>
<phone>(011) 123-4567</phone>
XML Schema
XML Schema is commonly known as XML Schema Definition (XSD). It
is used to describe and validate the structure and the content of XML
data. XML schema defines the elements, attributes, and data types.
Schema element supports Namespaces. It is similar to a database schema
that describes the data in a database.

Syntax
You need to declare a schema in your XML document as follows:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

Example
The following example shows how to use schema:

<?xml version="1.0" encoding="UTF-8"?>


<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="contact">
<xs:complexType>
<xs:sequence>
<xs:element name="name"
type="xs:string" /> <xs:element
name="company" type="xs:string" />
<xs:element name="phone" type="xs:int"
/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

The basic idea behind XML Schemas is that they describe the legitimate format that an
XML document can take.

Elements
Elements are the building blocks of XML document. An element can be defined within an
XSD as follows:

<xs:element name="x" type="y"/>


XML

Definition Types
You can define XML schema elements in the following ways:

Simple Type
Simple type element is used only in the context of the text. Some of the predefined
simple types are: xs:integer, xs:boolean, xs:string, xs:date. For example:

<xs:element name="phone_number" type="xs:int" />

Complex Type
A complex type is a container for other element definitions. This allows you to specify
which child elements an element can contain and to provide some structure within your
XML documents. For example:

<xs:element name="Address">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />

<xs:element name="phone" type="xs:int" />


</xs:sequence>
</xs:complexType>
</xs:element>

In the above example, Address element consists of child elements. This is a container for
other <xs:element> definitions, that allows to build a simple hierarchy of elements in
the XML document.

Global Types
With the global type, you can define a single type in your document, which can be used
by all other references. For example, suppose you want to generalize the person and
company for different addresses of the company. In such case, you can define a general
type as follows:

<xs:element name="AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
XML

Now let us use this type in our example as follows:

<xs:element name="Address1">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType" />
<xs:element name="phone1" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Address2">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType" />
<xs:element name="phone2" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>

Instead of having to define the name and the company twice (once for Address1 and once
for Address2), we now have a single definition. This makes maintenance simpler, i.e., if you
decide to add "Postcode" elements to the address, you need to add them at just one place.

Attributes
Attributes in XSD provide extra information within an element. Attributes have name and
type property as shown below:

<xs:attribute name="x" type="y"/>


XML Schema Example
Let's create a schema file.

employee.xsd

1. <?xml version="1.0"?>
2. <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
3. targetNamespace="http://www.abc.com"
4. xmlns="http://www.abc.com"
5. elementFormDefault="qualified">
6. <xs:element name="employee">
7. <xs:complexType>
8. <xs:sequence>
9. <xs:element name="firstname" type="xs:string"/>
10. <xs:element name="lastname" type="xs:string"/>
11. <xs:element name="email" type="xs:string"/>
12. </xs:sequence>
13. </xs:complexType>
14. </xs:element>
15. </xs:schema>

Let's see the xml file using XML schema or XSD file.

employee.xml

1. <?xml version="1.0"?>
2. <employee
3. xmlns="http://www.abc.com"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xsi:schemaLocation="http://www.abc.com employee.xsd">
6. <firstname>vimal</firstname>
7. <lastname>jaiswal</lastname>
8. <email>[email protected]</email>
9. </employee>
Description of XML Schema
<xs:element name="employee"> : It defines the element name employee.

<xs:complexType> : It defines that the element 'employee' is complex type.

<xs:sequence> : It defines that the complex type is a sequence of elements.

<xs:element name="firstname" type="xs:string"/> : It defines that the


element 'firstname' is of string/text type.

<xs:element name="lastname" type="xs:string"/> : It defines that the


element 'lastname' is of string/text type.

<xs:element name="email" type="xs:string"/> : It defines that the element


'email' is of string/text type.

DTD vs XSD
There are many differences between DTD (Document Type Definition) and XSD (XML Schema
Definition). In short, DTD provides less control on XML structure whereas XSD (XML schema) provides
more control.

The important differences are given below:

No. DTD XSD

1) DTD stands for Document Type XSD stands for XML Schema Definition.
Definition.

2) DTDs are derived XSDs are written in XML.


from SGML syntax.

3) DTD doesn't support XSD supports datatypes for elements and


datatypes. attributes.

4) DTD doesn't support XSD supports namespace.


namespace.

5) DTD doesn't define order for XSD defines order for child elements.
child elements.

6) DTD provides less control on XSD provides more control on XML structure.
XML structure.
SAMPLE.xsd

<?xml version="1.0" encoding="UTF-8" ?>


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
<?xml version="1.0" encoding="UTF-8"?>
<shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="SAMPLE.xsd">
<orderperson>John Smith</orderperson>
<shipto>
<name>Ola Nordmann</name>
<address>Langgt 23</address>
<city>4000 Stavanger</city>
<country>Norway</country>
</shipto>
</shiporder>
XML tree structure
An XML document is always descriptive. The tree structure is often referred to as XML Tree
and plays an important role to describe any XML document easily.

The tree structure contains root (parent) elements, child elements, and so on. By using tree
structure, you can get to know all succeeding branches and sub-branches starting from the
root. The parsing starts at the root, then moves down the first branch to an element, take
the first branch from there, and so on to the leaf nodes.

Example
Following example demonstrates simple XML tree structure:

<?xml version="1.0"?>
<Company>
<Employee>
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
<Email>[email protected]</Email>
<Address>
<City>Bangalore</City>
<State>Karnataka</State>
<Zip>560212</Zip>
</Address>
</Employee>
</Company>

Following tree structure represents the above XML document:


In the above diagram, there is a root element named as <company>. Inside that, there is
one more element <Employee>. Inside the employee element, there are five branches
named <FirstName>, <LastName>, <ContactNo>, <Email>, and <Address>. Inside the
<Address> element, there are three sub-branches, named <City> <State> and <Zip>.
XML DOM

The Document Object Model (DOM) is the foundation of XML. XML


documents have a hierarchy of informational units called nodes; DOM is a
way of describing those nodes and the relationships between them.

A DOM document is a collection of nodes or pieces of information organized


in a hierarchy. This hierarchy allows a developer to navigate through the
tree looking for specific information. Because it is based on a hierarchy of
information, the DOM is said to be tree based.

The XML DOM, on the other hand, also provides an API that allows a
developer to add, edit, move, or remove nodes in the tree at any point in
order to create an application.

XML DOM - Navigation


Until now we studied DOM structure, how to load and parse XML DOM object and
traverse through the DOM objects. Here we will see how we can navigate between
nodes in a DOM object. The XML DOM consist of various properties of the nodes
which help us navigate through the nodes, such as

 parentNode
 childNodes
 firstChild
 lastChild
 nextSibling
 previousSibling
EXAMPLE for DOM-1:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
<html>
<body>
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
var xmlDoc = xml.responseXML;
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
}
</script>
</body>
</html>
EXAMPLE-2:
<?xml version="1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>AbcTechnologies</company>
<phone>(011) 123-4567</phone>
</contact-info>
<html>
<body>
<h1>AbcTechnologies DOM example </h1>
<div>
<b>Name:</b> <span id="name"></span><br> <b>Company:</b>
<span id="company"></span><br> <b>Phone:</b> <span
id="phone"></span>
</div>
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","address.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("name").innerHTML=
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById("company").innerHTML=
xmlDoc.getElementsByTagName("company")[0].childNodes[0].nodeVa
lue;
document.getElementById("phone").innerHTML=
xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue
;
</script>
</body>
</html>
1. XSLT – Overview XSLT

XSL
Before learning XSLT, we should first understand XSL which stands for EXtensible
Stylesheet Language. It is similar to XML as CSS is to HTML.

Need for XSL


In case of HTML document, tags are predefined such as table, div, and span; and the browser
knows how to add style to them and display those using CSS styles. But in case of XML
documents, tags are not predefined. In order to understand and style an XML document, World
Wide Web Consortium (W3C) developed XSL which can act as XML based Stylesheet Language.
An XSL document specifies how a browser should render an XML document.

Following are the main parts of XSL:

 XSLT - used to transform XML document into various other types of document.

 XPath - used to navigate XML document.

 XSL-FO - used to format XML document.

What is XSLT
XSLT, Extensible Stylesheet Language Transformations, provides the ability to transform
XML data from one format to another automatically.

How XSLT Works


An XSLT stylesheet is used to define the transformation rules to be applied on the target
XML document. XSLT stylesheet is written in XML format. XSLT Processor takes the XSLT
stylesheet and applies the transformation rules on the target XML document and then it
generates a formatted document in the form of XML, HTML, or text format. This formatted
document is then utilized by XSLT formatter to generate the actual output which is to be
displayed to the end-user.

1
XSLT

Advantages
Here are the advantages of using XSLT:

 Independent of programming. Transformations are written in a separate xsl file


which is again an XML document.

 Output can be altered by simply modifying the transformations in xsl file. No need to
change any code. So Web designers can edit the stylesheet and can see the change
in the output quickly.

2
2. XSLT – Syntax XSLT

Let’s suppose we have the following sample XML file, students.xml, which is required to be
transformed into a well-formatted HTML document.

students.xml
<?xml version="1.0"?>
<class>
<student rollno="393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>

We need to define an XSLT style sheet document for the above XML document to meet the
following criteria:

 Page should have a title Students.



 Page should have a table of student details.

 Columns should have following headers: Roll No, First Name, Last Name, Nick Name,
Marks

 Table must contain details of the students accordingly.

3
XSLT

Step 1: Create XSLT document


Create an XSLT document to meet the above requirements, name it as students.xsl and
save it in the same location where students.xml lies.

students.xsl
<?xml version="1.0" encoding="UTF-8"?>
<!-- xsl stylesheet declaration with xsl namespace:
Namespace tells the xlst processor about which element is to be processed
and which is used for output purpose only
-->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- xsl template declaration:

template tells the xlst processor about the section of xml document which is to be
formatted. It takes an XPath expression.

In our case, it is matching document root element and will tell processor to
process the entire document with this template.
-->
<xsl:template match="/">
<!-- HTML tags

Used for formatting purpose. Processor will skip them and browser will
simply render them.
-->
<html>
<body>
<h2>Students</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>
<!-- for-each processing instruction
Looks for each element matching the XPAth expression
-->

4
XSLT

<xsl:for-each select="class/student">
<tr>
<td>
<!-- value-of processing instruction

process the value of the element matching the XPath expression


-->
<xsl:value-of select="@rollno"/>
</td>

<td><xsl:value-of select="firstname"/></td>
<td><xsl:value-of select="lastname"/></td>
<td><xsl:value-of select="nickname"/></td>
<td><xsl:value-of select="marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

Step 2: Link the XSLT Document to the XML Document


Update student.xml document with the following xml-stylesheet tag. Set href value to
students.xsl

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<class>
...
</class>

5
XSLT

Step 3: View the XML Document in Internet Explorer

students.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<class>
<student rollno="393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>

6
XSLT

Output
XPath uses path expressions to select nodes in an XML document.
The node is selected by following a path or steps. The most useful path
expressions are listed below:

Expression Description

nodename Selects all nodes with the name "nodename"

/ Selects from the root node

// Selects nodes in the document from the current node


that match the selection no matter where they are

. Selects the current node

.. Selects the parent of the current node

@ Selects attributes
3. XSLT – Template XSLT

<xsl:template> defines a way to reuse templates in order to generate the desired output
for nodes of a particular type/context.

Declaration
Following is the syntax declaration of <xsl:template> element.

<xsl:template
name= Qname
match = Pattern
priority = number
mode = QName >
</xsl:template>

Attributes
Name Description

name Name of the element on which template is to be applied.

match Pattern which signifies the element(s) on which template is to be applied.

Priority number of a template. Matching template with low priority is not


priority
considered in from in front of high priority template.

Allows element to be processed multiple times to produce a different


mode
result each time.

Elements
Number of
occurrences Unlimited

Parent
xsl:stylesheet, xsl:transform
elements

xsl:apply-imports,xsl:apply-templates, xsl:attribute, xsl:call-template,


Child xsl:choose, xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:fallback,
elements xsl:for-each, xsl:if, xsl:message, xsl:number, xsl:param, xsl:processing-
instruction, xsl:text, xsl:value-of, xsl:variable, output elements

8
XSLT

Demo Example
This template rule has a pattern that identifies <student> elements and produces an output
in a tabular format.

students.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<class>
<student rollno="393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>

9
XSLT

students_imports.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>Students</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>
<xsl:for-each select="class/student">
<tr>
<td>
<xsl:value-of select="@rollno"/>
</td>

<td><xsl:value-of select="firstname"/></td>
<td><xsl:value-of select="lastname"/></td>
<td><xsl:value-of select="nickname"/></td>
<td><xsl:value-of select="marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

10
XSLT

Output

11
4. XSLT – <value-of> XSLT

<xsl:value-of> tag puts the value of the selected node as per XPath expression, as text.

Declaration
Following is the syntax declaration of <xsl:value-of> element

<xsl:value-of
select = Expression
disable-output-escaping = "yes" | "no" >
</xsl:value-of>

Attributes
Name Description

Select XPath Expression to be evaluated in current context.

disable-
Default-"no". If "yes", output text will not escape xml characters from
output-
text.
escaping

Elements
Number of
Unlimited
occurrences

xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:for-


Parent each, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing-
elements instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param,
output elements

Child elements None

Demo Example
This example creates a table of <student> element with its attribute rollno and its child
<firstname>, <lastname>, <nickname>, and <marks>.

12
XSLT

students.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<class>
<student rollno="393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>

13
XSLT

students.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>Students</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>
<xsl:for-each select="class/student">
<tr>
<td>
<xsl:value-of select="@rollno"/>
</td>

<td><xsl:value-of select="firstname"/></td>
<td><xsl:value-of select="lastname"/></td>
<td><xsl:value-of select="nickname"/></td>
<td><xsl:value-of select="marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

14
XSLT

Verify the output

15
5. XSLT – <for-each> XSLT

<xsl:for-each> tag applies a template repeatedly for each node.

Declaration
Following is the syntax declaration of <xsl:for-each> element

<xsl:for-each
select = Expression >
</xsl:for-each>

Attributes
Name Description

select XPath Expression to be evaluated in current context to determine the set of


nodes to be iterated.

Elements
Number of
Unlimited
occurrences

xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:for-


Parent each, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing-
elements instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output
elements

xsl:apply-imports, xsl:apply-templates, xsl:attribute, xsl:call-template,


Child xsl:choose, xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:fallback,
elements xsl:for-each, xsl:if, xsl:message, xsl:number, xsl:processing-instruction,
xsl:sort, xsl:text, xsl:value-of, xsl:variable

16
XSLT

Demo Example
This example creates a table of <student> element with its attribute rollno and its child
<firstname>, <lastname>, <nickname> and <marks> by iterating over each student.

students.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<class>
<student rollno="393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>

students.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>

17
XSLT

<body>
<h2>Students</h2>

<table border="1">
<tr bgcolor="#9acd32">
<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>
<xsl:for-each select="class/student">
<tr>
<td>
<xsl:value-of select="@rollno"/>
</td>

<td><xsl:value-of select="firstname"/></td>
<td><xsl:value-of select="lastname"/></td>
<td><xsl:value-of select="nickname"/></td>
<td><xsl:value-of select="marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

18
XSLT

Output

19
6. XSLT – <sort> XSLT

<xsl:sort> tag specifies a sort criteria on the nodes.

Declaration
Following is the syntax declaration of <xsl:sort> element.

<xsl:sort
select = string-expression
lang = { nmtoken }
data-type = { "text" | "number" | QName }
order = { "ascending" | "descending" }
case-order = { "upper-first" | "lower-first" } >
</xsl:sort>

Attributes
Name Description

select Sorting key of the node.

lang Language alphabet used to determine sort order.

data-type Data type of the text.

order Sorting order. Default is "ascending"

case-order Sorting order of string by capitalization. Default is "upper-first".

Elements
Number of occurrences Unlimited

Parent elements xsl:apply-templates, xsl:for-each

Child elements None

20
XSLT

Demo Example
This example creates a table of <student> element with its attribute rollno and its child
<firstname>, <lastname>, <nickname>, and <marks> by iterating over each student sort
them by first name.

students.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<class>
<student rollno="393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>

21
XSLT

students.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>Students</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>
<xsl:for-each select="class/student">
<xsl:sort select="firstname"/>
<tr>
<td>
<xsl:value-of select="@rollno"/>
</td>

<td><xsl:value-of select="firstname"/></td>
<td><xsl:value-of select="lastname"/></td>
<td><xsl:value-of select="nickname"/></td>
<td><xsl:value-of select="marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

22
XSLT

Output

23
7. XSLT – <if> XSLT

<xsl:if> tag specifies a conditional test against the content of nodes.

Declaration
Following is the syntax declaration of <xsl:if> element.

<xsl:if
test = boolean-expression >
</xsl:if>

Attributes
Name Description

test The condition in the xml data to test.

Elements
Number of
Unlimited
occurrences

xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:for-


Parent each, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing-
elements instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output
elements

xsl:apply-templates, xsl:attribute, xsl:call-template, xsl:choose,


Child xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:for-each, xsl:if,
elements xsl:processing-instruction, xsl:text, xsl:value-of, xsl:variable, output
elements

Demo Example
This example creates a table of <student> element with its attribute rollno and its child
<firstname>, <lastname>, <nickname>, and <marks> by iterating over each student. It
checks marks to be greater than 90 and then prints the student(s) details.

24
XSLT

students.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<class>
<student rollno="393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>

students.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>Students</h2>
<table border="1">
<tr bgcolor="#9acd32">

25
XSLT

<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>
<xsl:for-each select="class/student">
<xsl:if test="marks > 90">
<tr>
<td>
<xsl:value-of select="@rollno"/>
</td>

<td><xsl:value-of select="firstname"/></td>
<td><xsl:value-of select="lastname"/></td>
<td><xsl:value-of select="nickname"/></td>
<td><xsl:value-of select="marks"/></td>
</tr>
</xsl:if>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

26
XSLT

Output

27
8. XSLT – <choose> XSLT

<xsl:choose> tag specifies a multiple conditional tests against the content of nodes in
conjunction with the <xsl:otherwise> and <xsl:when> elements.

Declaration
Following is the syntax declaration of <xsl:choose> element.

<xsl:choose >
</xsl:choose>

Elements
Number of
Unlimited
occurrences

xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:for-


Parent each, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing-
elements instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param,
output elements

Child elements xsl:otherwise, xsl:when

Demo Example
This example creates a table of <student> element with its attribute rollno and its child
<firstname>, <lastname>, <nickname>, and <marks> by iterating over each student. It
checks and then prints the grade details.

students.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<class>
<student rollno="393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">

28
XSLT

<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>

students.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Students</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
<th>Grade</th>
</tr>
<xsl:for-each select="class/student">
<tr>
<td>
<xsl:value-of select="@rollno"/>
</td>

29
XSLT

<td><xsl:value-of select="firstname"/></td>
<td><xsl:value-of select="lastname"/></td>
<td><xsl:value-of select="nickname"/></td>
<td><xsl:value-of select="marks"/></td>
<td>
<xsl:choose>
<xsl:when test="marks > 90">
High
</xsl:when>
<xsl:when test="marks > 85">
Medium
</xsl:when>
<xsl:otherwise>
Low
</xsl:otherwise>
</xsl:choose>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

30
XSLT

Output

31
9. XSLT – <key> XSLT

<xsl:key> tag element specifies a named name-value pair assigned to a specific element in
an XML document. This key is used with the key() function in XPath expressions to access
the assigned elements in an XML document.

Declaration
Following is the syntax declaration of <xsl:key> element

<xsl:key
name = QName
match = Pattern
use = Expression >
</xsl:key>

Attributes
Name Description

Name Name of the key to be used.

Match Patterns used to identify a node that holds this key.

Use XPath expression to identify the value of the nodes of xml document.

Elements
Number of
occurrences Unlimited

Parent elements xsl:stylesheet

Child elements None

Demo Example
This example creates a table of <student> element with its attribute rollno and its child
<firstname>, <lastname>, <nickname>, and <marks> by iterating over each student. It
checks key as firstname to be one of the student's name and then prints the student details.
32
XSLT

students.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<class>
<student rollno="393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>

students.xsl
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:key name="firstname-search" match="student" use="firstname"/>


<xsl:template match="/">
<html>
<body>
<h2>Students</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Roll No</th>

33
XSLT

<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>
<xsl:for-each select="key('firstname-search', 'Dinkar')">
<tr>
<td>
<xsl:value-of select="@rollno"/>
</td>

<td><xsl:value-of select="firstname"/></td>
<td><xsl:value-of select="lastname"/></td>
<td><xsl:value-of select="nickname"/></td>
<td><xsl:value-of select="marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

Output

34
Web Programming Step by Step
Chapter 10
Ajax and XML for Accessing Data
Except where otherwise noted, the contents of this presentation are Copyright 2009 Marty Stepp and Jessica
Miller.

10.1: Ajax Concepts


10.1: Ajax Concepts
10.2: Using XMLHttpRequest
10.3: XML
Synchronous web communication (10.1)

synchronous: user must wait while new pages load


the typical communication pattern used in web pages (click, wait, refresh)

Web applications
web application: a web site that mimics the look, feel, and overall user experience of a desktop
application
a web app presents a continuous user experience rather than disjoint pages
as much as possible, "feels" like a normal program to the user
examples of web apps
Gmail, Google Maps, Google Docs and Spreadsheets, Flickr, A9
many web apps use Ajax to battle these problems of web pages:
slowness / lack of UI responsiveness
lack of user-friendliness
jarring nature of "click-wait-refresh" pattern
What is Ajax?
Ajax: Asynchronous JavaScript and XML

not a programming language; a particular way of using JavaScript


downloads data from a server in the background
allows dynamically updating a page without making the user wait
aids in the creation of rich, user-friendly web sites
examples: UW's CSE 14x Diff Tool, Practice-It; Google Suggest

Asynchronous web communication

asynchronous: user can keep interacting with page while data loads
communication pattern made possible by Ajax

Core Ajax concepts


JavaScript's XMLHttpRequest object can fetch files from a web server
supported in IE5+, Safari, Firefox, Opera (with minor compatibilities)
it can do this asynchronously (in the background, transparent to user)
contents of fetched file can be put into current web page using DOM
result: user's web page updates dynamically without a page reload
A typical Ajax request
1. user clicks, invoking event handler
2. that handler's JS code creates an XMLHttpRequest
object
3. XMLHttpRequest object requests a document from
a web server
4. server retrieves appropriate data, sends it back
5. XMLHttpRequest fires event to say that the data has
arrived
this is often called a callback
you can attach a handler to be notified when the
data has arrived
6. your callback event handler processes the data and displays it

10.2: Using XMLHttpRequest


10.1: Ajax Concepts
10.2: Using XMLHttpRequest
10.3: XML
The XMLHttpRequest object
the core JavaScript object that makes Ajax possible

methods: abort, getAllResponseHeaders, getResponseHeader, open, send,


setRequestHeader
properties: onreadystatechange, readyState, responseText, responseXML,
status, statusText
IE6 doesn't follow standards and uses its own ActiveXObject instead
we'll learn to use Ajax in 4 steps:
1. synchronous, text-only (SJAT?)
2. asynchronous, text-only (AJAT?)
3. asynchronous w/ Prototype (AJAP?)
4. asynchronous w/ XML data (real Ajax)

1. Synchronous requests (10.2.1)


var ajax = new XMLHttpRequest();
ajax.open("GET", url, false);
ajax.send(null);

// at this point, the request will have returned with its data
do something with ajax.responseText;

create the request object, open a connection, send the request


when send returns, the fetched text will be stored in request's responseText property
Why synchronous requests are bad
your code waits for the request to completely finish
before proceeding
easier for you to program, but ...
the user's entire browser locks up until the download is
completed
a terrible user experience (especially if the file is very
large)

2. Asynchronous requests, basic idea (10.2.3)


var ajax = new XMLHttpRequest();
ajax.onreadystatechange = functionName;
ajax.open("get", url, true);
ajax.send(null);

// don't process ajax.responseText here, but in your function


...

attach an event handler to the request's onreadystatechange event


pass true as third parameter to open
handler will be called when request state changes, e.g. finishes
function's code will be run when request is complete
The readyState property
holds the status of the XMLHttpRequest
possible values for the readyState property:
State Description
0 not initialized
1 set up
2 sent
3 in progress
4 complete
readyState changes → onreadystatechange handler runs
usually we are only interested in readyState of 4 (complete)

Asynchronous XMLHttpRequest template


var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) { // 4 means request is finished
do something with ajax.responseText;
}
};
ajax.open("get", url, true);
ajax.send(null);

most Ajax code uses an anonymous function as the event handler


useful to declare it as an inner anonymous function, because then it can access surrounding local
variables (e.g. ajax)
Checking for request errors (10.2.2)
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
if (ajax.status == 200) { // 200 means request succeeded
do something with ajax.responseText;
} else {
code to handle the error;
}
}
};
ajax.open("get", url, true);
ajax.send(null);

web servers return status codes for requests (200 means Success)
you may wish to display a message or take action on a failed request

Prototype's Ajax model (10.2.4)


new Ajax.Request(
"url",
{
option : value,
option : value,
...
option : value
}
);

Prototype's Ajax.Request object constructor accepts 2 parameters:


1. the URL to fetch, as a String,
2. a set of options, as an array of key:value pairs in {} braces
hides some of the icky details (onreadystatechange, etc.)
works in all browsers: IE, Firefox, etc.
Prototype Ajax methods and properties
options that can be passed to the Ajax.Request constructor:
method : how to fetch the request from the server (default "post")
parameters : query parameters to pass to the server, if any
asynchronous (default true), contentType, encoding, requestHeaders
events in the Ajax.Request object that you can handle:
onSuccess : request completed successfully
onFailure : request was unsuccessful
onCreate, onComplete, onException, on### (handler for HTTP error code ###)

Prototype Ajax template


new Ajax.Request(
"url",
{
method: "get",
onSuccess: functionName
}
);
...

function functionName(ajax) {
do something with ajax.responseText;
}

most Ajax requests we'll do in this course are GET requests


attach a handler to the request's onSuccess event
the handler accepts the XMLHttpRequest object, ajax, as a parameter

You might also like