0% found this document useful (0 votes)
36 views189 pages

IP-Unit 4 & 5

The document discusses PHP and XML. It provides an overview of PHP including its history, uses, characteristics and basic syntax. It also covers PHP variables and data types. For XML, it mentions DOM, XSLT transformation, and RSS/ATOM feeds. The document contains detailed information about PHP and XML.

Uploaded by

ummonica08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views189 pages

IP-Unit 4 & 5

The document discusses PHP and XML. It provides an overview of PHP including its history, uses, characteristics and basic syntax. It also covers PHP variables and data types. For XML, it mentions DOM, XSLT transformation, and RSS/ATOM feeds. The document contains detailed information about PHP and XML.

Uploaded by

ummonica08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 189

CS8651-Internet Programming-UNIT IV Notes-N.

Mohammed Haris

UNIT IV PHP and XML 8 An introduction to PHP: PHP- Using PHP- Variables-Program
control- Built-in functions-Connecting to Database – Using Cookies-Regular Expressions; XML:
Basic XML- Document Type Definition- XML Schema DOM and Presenting XML, XML Parsers
and Validation, XSL and XSLT Transformation, News Feed (RSS and ATOM).

PHP: Hypertext Preprocessor

• PHP started out as a small open source project that evolved as more and more people
found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way
back in 1994.
• PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
• PHP is a server side scripting language that is embedded in HTML. It is used to
manage dynamic content, databases, session tracking, even build entire e-commerce
sites.
• It is integrated with a number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
• PHP is pleasingly zippy in its execution, especially when compiled as an Apache
module on the Unix side. The MySQL server, once started, executes even very
complex queries with huge result sets in record-setting time.
• PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP4 added support for Java and distributed object architectures (COM and
CORBA), making n-tier development a possibility for the first time.
• PHP is forgiving: PHP language tries to be as forgiving as possible.
• PHP Syntax is C-Like.
Common uses of PHP
• PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
• PHP can handle forms, i.e. gather data from files, save data to a file, thru email we
can send data, return data to the user.
• We add, delete, modify elements within wer database thru PHP.
• Access cookies variables and set cookies.
• Using PHP, we can restrict users to access some pages of wer website.
• It can encrypt data.
Characteristics of PHP
• Simplicity
• Efficiency
• Security
• Flexibility
• Familiarity
"Hello World" Script in PHP
<html>
<head>
<title>Hello World</title>

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<body>
<?php echo "Hello, World!";?>
</body>
</html>
It will produce following result:
Hello, World!
• If we examine the HTML output of the above example, the PHP code is not present in
the file sent from the server to wer Web browser. All of the PHP present in the Web
page is processed and stripped from the page; the only thing returned to the client
from the Web server is pure HTML output.
• All PHP code must be included inside one of the three special markup tags ate are
recognised by the PHP Parser.
<?php PHP code goes here ?>

<? PHP code goes here ?>

<script language="php"> PHP code goes here </script>


In order to develop and run PHP Web pages three vital components need to be installed
on wer computer system.
• Web Server - PHP will work with virtually all Web Server software, including
Microsoft's Internet Information Server (IIS) but then most often used is freely
availble Apache Server. Download Apache for free
here:http://httpd.apache.org/download.cgi
• Database - PHP will work with virtually all database software, including Oracle and
Sybase but most commonly used is freely available MySQL database. Download
MySQL for free here: http://www.mysql.com/downloads/index.html
• PHP Parser - In order to process PHP script instructions a parser must be installed to
generate HTML output that can be sent to the Web Browser. This tutorial will guide
we how to install PHP parser on wer computer.

Basic PHP Syntax


• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>

• The default file extension for PHP files is ".php".


• A PHP file normally contains HTML tags, and some PHP scripting code.
• Below, we have an example of a simple PHP file, with a PHP script that uses a built-
in PHP function "echo" to output the text "Hello World!" on a web page:
<!DOCTYPE html>
<html>
<body>

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

Comments in PHP
• A comment in PHP code is a line that is not read/executed as part of the program. Its
only purpose is to be read by someone who is looking at the code.
• PHP supports several ways of commenting:
<!DOCTYPE html>
<html>
<body>

<?php
// This is a single-line comment

# This is also a single-line comment

/*
This is a multiple-lines comment block
that spans over multiple
lines
*/

// We can also use comments to leave out parts of a code line


$x = 5 /* + 15 */ + 5;
echo $x;
?>

</body>
</html>

PHP Case Sensitivity


• In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-
defined functions are NOT case-sensitive.
• All variable names are case-sensitive.
• In the example below, all three echo statements below are legal (and equal):
<!DOCTYPE html>
<html>
<body>

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

</body>
</html>
• However; In the example below, only the first statement will display the value of the
$color variable (this is because $color, $COLOR, and $coLOR are treated as three
different variables):
<!DOCTYPE html>
<html>
<body>

<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>

</body>
</html>

PHP - Variable Types


• The main way to store information in the middle of a PHP program is by using a
variable.
• Here are the most important things to know about variables in PHP.
• All variables in PHP are denoted with a leading dollar sign ($).
• The value of a variable is the value of its most recent assignment.
• Variables are assigned with the = operator, with the variable on the left-hand side and
the expression to be evaluated on the right.
• Variables can, but do not need, to be declared before assignment.
• Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
• Variables used before they are assigned have default values.
• PHP does a good job of automatically converting types from one to another when
necessary.
• PHP variables are Perl-like.
• PHP has a total of eight data types which we use to construct our variables:
o Integers: are whole numbers, without a decimal point, like 4195.
o Doubles: are floating-point numbers, like 3.14159 or 49.1.
o Booleans: have only two possible values either true or false.
o NULL: is a special type that only has one value: NULL.
4

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

o Strings: are sequences of characters, like 'PHP supports string operations.'


o Arrays: are named and indexed collections of other values.
o Objects: are instances of programmer-defined classes, which can package up
both other kinds of values and functions that are specific to the class.
o Resources: are special variables that hold references to resources external to
PHP (such as database connections).
• The first five are simple types, and the next two (arrays and objects) are compound -
the compound types can package up other arbitrary values of arbitrary type, whereas
the simple types cannot.
Integers
o They are whole numbers, without a decimal point, like 4195. They are the
simplest type .they correspond to simple whole numbers, both positive and
negative. Integers can be assigned to variables, or they can be used in
expressions, like so:
$int_var = 12345;
$another_int = -12345 + 12345;
• Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16)
format. Decimal format is the default, octal integers are specified with a
leading 0, and hexadecimals have a leading 0x.
• For most common platforms, the largest integer is (2**31 . 1) (or
2,147,483,647), and the smallest (most negative) integer is . (2**31 . 1) (or
.2,147,483,647).
Doubles
• They like 3.14159 or 49.1. By default, doubles print with the minimum
number of decimal places needed. For example, the code:
<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print("$many + $many_2 = $few <br>");
?>
It produces the following browser output:
2.28888 + 2.21112 = 4.5
Boolean
• They have only two possible values either true or false. PHP provides a couple
of constants especially for use as Booleans: TRUE and FALSE, which can be
used like so:
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
• Interpreting other types as Booleans
• Here are the rules for determine the "truth" of any value not already of the
Boolean type:
• If the value is a number, it is false if exactly equal to zero and true otherwise.

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• If the value is a string, it is false if the string is empty (has zero characters) or
is the string "0", and is true otherwise.
• Values of type NULL are always false.
• If the value is an array, it is false if it contains no other values, and it is true
otherwise. For an object, containing a value means having a member variable
that has been assigned a value.
• Valid resources are true (although some functions that return resources when
they are successful will return FALSE when unsuccessful).
• Don't use double as Booleans.
• Each of the following variables has the truth value embedded in its name
when it is used in a Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";
NULL
• NULL is a special type that only has one value: NULL. To give a variable the NULL
value, simply assign it like this:
$my_var = NULL;
• The special constant NULL is capitalized by convention, but actually it is case
insensitive; we could just as well have typed:
$my_var = null;
• A variable that has been assigned NULL has the following properties:
• It evaluates to FALSE in a Boolean context.
• It returns FALSE when tested with IsSet() function.
Strings
• They are sequences of characters, like "PHP supports string operations". Following
are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
• Singly quoted strings are treated almost literally, whereas doubly quoted strings
replace variables with their values as well as specially interpreting certain character
sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!';
print($literally);
print "<br>";
$literally = 'My $variable will print!';
print($literally);
?>

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

This will produce following result:


My $variable will not print!\n
My name will print
There are no artificial limits on string length - within the bounds of available memory, we
ought to be able to make arbitrarily long strings.
• Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP:
• Certain character sequences beginning with backslash (\) are replaced with special
characters
• Variable names (starting with $) are replaced with string representations of their
values.
• The escape-sequence replacements are:
o \n is replaced by the newline character
o \r is replaced by the carriage-return character
o \t is replaced by the tab character
o \$ is replaced by the dollar sign itself ($)
o \" is replaced by a single double-quote (")
o \\ is replaced by a single backslash (\)
Variable Scope
Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types:
• Local variables
• Function parameters
• Global variables
• Static variables
• Variable Naming
Rules for naming a variable is:
• Variable names must begin with a letter or underscore character.
• A variable name can consist of numbers, letters, underscores but we cannot use
characters like + , - , % , ( , ) . & , etc
• There is no size limit for variables.

PHP - Constants
• A constant is a name or an identifier for a simple value. A constant value cannot
change during the execution of the script. By default a constant is case-sensitiv. By
convention, constant identifiers are always uppercase. A constant name starts with a
letter or underscore, followed by any number of letters, numbers, or underscores. If
we have defined a constant, it can never be changed or undefined.
• To define a constant we have to use define() function and to retrieve the value of a
constant, we have to simply specifying its name. we do not need to have a constant
with a $, but we can also use the function constant() to read a constant's
• constant() function
• As indicated by the name, this function will return the value of the constant.

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• This is useful when we want to retrieve value of a constant, but we do not know its
name, i.e. It is stored in a variable or returned by a function.
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>

• Only scalar data (boolean, integer, float and string) can be contained in constants.
• Differences between constantsand variables are
• There is no need to write a dollar sign ($) before a constant, where as in Variable one
has to write a dollar sign.
• Constants cannot be defined by simple assignment, they may only be defined using
the define() function.
• Constants may be defined and accessed anywhere without regard to variable scoping
rules.
• Once the Constants have been set, may not be redefined or undefined.
• Valid and invalid constant names
// Valid constant names
define("ONE", "first thing");
define("TWO2", "second thing");
define("THREE_3", "third thing")
// Invalid constant names
define("2TWO", "second thing");
define(" THREE ", "third value");

PHP - Operator Types


PHP language supports following type of operators.
• Arithmetic Operators
• Comparision Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Arithmetic Operators
• There are following arithmatic operators supported by PHP language:
• Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the A - B will give -10
first
* Multiply both operands A * B will give 200
/ Divide numerator by denumerator B / A will give 2
% Modulus Operator and remainder of B % A will give 0
after an integer division

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

++ Increment operator, increases A++ will give 11


integer value by one
-- Decrement operator, decreases A-- will give 9
integer value by one
Comparison Operators
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
== Checks if the value of two operands (A == B) is not true.
are equal or not, if yes then condition
becomes true.
!= Checks if the value of two operands (A != B) is true.
are equal or not, if values are not equal
then condition becomes true.
> Checks if the value of left operand is (A > B) is not true.
greater than the value of right operand,
if yes then condition becomes true.
< Checks if the value of left operand is (A < B) is true.
less than the value of right operand, if
yes then condition becomes true.
>= Checks if the value of left operand is (A >= B) is not true.
greater than or equal to the value of
right operand, if yes then condition
becomes true.
<= Checks if the value of left operand is (A <= B) is true.
less than or equal to the value of right
operand, if yes then condition becomes
true.
Logical Operators
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
and Called Logical AND operator. If (A and B) is true.
both the operands are true then then
condition becomes true.
or Called Logical OR Operator. If any (A or B) is true.
of the two operands are non zero then
then condition becomes true.
&& Called Logical AND operator. If (A && B) is true.
both the operands are non zero then then
condition becomes true.
|| Called Logical OR Operator. If any (A || B) is true.
of the two operands are non zero then
then condition becomes true.
! Called Logical NOT Operator. Use !(A && B) is false.
to reverses the logical state of its

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

operand. If a condition is true then


Logical NOT operator will make false.
Assignment Operators
There are following assignment operators supported by PHP language:
Operator Description Example
= Simple assignment operator, C = A + B will assigne value of A + B
Assigns values from right side into C
operands to left side operand
+= Add AND assignment operator, C += A is equivalent to C = C + A
It adds right operand to the left
operand and assign the result to left
operand
-= Subtract AND assignment C -= A is equivalent to C = C - A
operator, It subtracts right operand
from the left operand and assign
the result to left operand
*= Multiply AND assignment C *= A is equivalent to C = C * A
operator, It multiplies right operand
with the left operand and assign the
result to left operand
/= Divide AND assignment C /= A is equivalent to C = C / A
operator, It divides left operand
with the right operand and assign
the result to left operand
%= Modulus AND assignment C %= A is equivalent to C = C % A
operator, It takes modulus using
two operands and assign the result
to left operand
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for
a true or false value and then execute one of the two given statements depending upon the result
of the evaluation. The conditional operator has this syntax:
Oper Description Example
ator
?: Conditional Expression If Condition is true ? Then value X :
Otherwise value Y
Operators Categories
• All the operators we have discussed above can be categorised into following
categories:
• Unary prefix operators, which precede a single operand.
• Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
• The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of the
first expression.
• Assignment operators, which assign a value to a variable.

10

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Precedence of PHP Operators


• Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than others;
for example, the multiplication operator has higher precedence than the addition
operator:
• For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has
higher precedence than + so it first get multiplied with 3*2 and then adds into 7.
• Here operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
will be evaluated first.
Category Operator Associativity
Unary ! ++ -- Right to left
Multiplicative */% Left to right
Additive +- Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= Right to left

PHP - Decision Making


PHP supports following three decision making statements:
• if...else statement - use this statement if we want to execute a set of code when a
condition is true and another if the condition is not true
• elseif statement - is used with the if...else statement to execute a set of code ifone of
several condition are true
• switch statement - is used if we want to select one of many blocks of code to be
executed, use the Switch statement. The switch statement is used to avoid long blocks
of if..elseif..else code.
The If...Else Statement
If we want to execute some code if a condition is true and another code if a condition is false,
use the if ... else statement.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Example
The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!":
<html>
<body>

11

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>

</html>
If more than one line should be executed if a condition is true/false, the lines should be
enclosed within curly braces:
<html>

<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See we on Monday!";
}
?>
</body>
</html>
The ElseIf Statement
If we want to execute some code if one of several conditions are true use the elseif statement
Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Example
The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";

12

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>
The Switch Statement
• If we want to select one of many blocks of code to be executed, use the Switch
statement.
• The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;

Example
The switch statement works in an unusual way. First it evaluates given expression then seeks
a lable to match the resulting value. If a matching value is found then the code associated with
the matching label will be executed or if none of the lables match then statement will will
execute any specified default code.
<html>
<body>
<?php
$d=date("D");
switch ($d)
{
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":

13

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

echo "Today is Wednesday";


break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
</body>
</html>

PHP - Loop Types


• Loops in PHP are used to execute the same block of code a specified number of
times. PHP supports following four loop types.
• for - loops through a block of code a specified number of times.
• while - loops through a block of code if and as long as a specified condition is true.
• do...while - loops through a block of code once, and then repeats the loop as long as a
special condition is true.
• foreach - loops through a block of code for each element in an array.

The for loop statement


The for statement is used when we know how many times we want to execute a statement or
a block of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}

• The initializer is used to set the start value for the counter of the number of loop
iterations. A variable may be declared here for this purpose and it is traditional to
name it $i.
Example
The following example makes five iterations and changes the assigned value of two variables
on each pass of the loop:

14

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<html>
<body>
<?php
$a = 0;
$b = 0;

for( $i=0; $i<5; $i++ )


{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?>
</body>
</html>
This will produce following result:
At the end of the loop a=50 and b=25

The while loop statement


• The while statement will execute a block of code if and as long as a test expression is
true.
• If the test expression is true then the code block will be executed. After the code has
executed the test expression will again be evaluated and the loop will continue until
the test expression is found to be false.
Syntax
while (condition)
{
code to be executed;
}

Example
This example decrements a variable value on each iteration of the loop and the counter
increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;

while( $i < 10)


{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );

15

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

?>
</body>
</html>

This will produce following result:


Loop stopped at i = 10 and num = 40

The do...while loop statement


• The do...while statement will execute a block of code at least once - it then will repeat
the loop as long as a condition is true.
Syntax
do
{
code to be executed;
}while (condition);

Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10:
<html>
<body>
<?php
$i = 0;
$num = 0;
do{
$i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 10

The foreach loop statement


• The foreach statement is used to loop through arrays. For each pass the value of the
current array element is assigned to $value and the array pointer is moved by one and
in the next pass next element will be processed.
Syntax
foreach (array as value)
{
code to be executed;

16

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Example
Try out following example to list out the values of an array.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>

This will produce following result:


Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

The break statement


• The PHP break keyword is used to terminate the execution of a loop prematurely.
• The break statement is situated inside the statement block. If gives we full control
and whenever we want to exit from the loop we can come out. After coming out of a
loop immediate statement to the loop will be executed.
Example
In the following example condition test becomes true when the counter value reaches 3 and
loop terminates.
<html>
<body>

<?php
$i = 0;

while( $i < 10)


{
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>

17

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

</html>

This will produce following result:


Loop stopped at i = 3

The continue statement


• The PHP continue keyword is used to halt the current iteration of a loop but it does
not terminate the loop.
• Just like the break statement the continue statement is situated inside the statement
block containing the code that the loop executes, preceded by a conditional test. For
the pass encountering continue statement, rest of the loop code is skipped and next
pass starts.
Example
In the following example loop prints the value of array but for which condition becomes true
it just skip the code and next value is printed.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result
Value is 1
Value is 2
Value is 4
Value is 5

PHP - Arrays
• An array is a data structure that stores one or more similar type of values in a single
value. For example if we want to store 100 numbers then instead of defining 100
variables its easy to define an array of 100 length.
• There are three different kind of arrays and each array value is accessed using an ID c
which is called array index.
• Numeric array - An array with a numeric index. Values are stored and accessed in
linear fashion
• Associative array - An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
• Multidimensional array - An array containing one or more arrays and values are
accessed using multiple indices

18

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• Numeric Array
• These arrays can store numbers, strings and any object but their index will be
prepresented by numbers. By default array index starts from zero.
• Following is the example showing how to create and access numeric arrays.
• Here we have used array() function to create array. This function is explained in
function reference.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value )


{
echo "Value is $value <br />";
}
?>
</body>
</html>

This will produce following result:


Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
• The associative arrays are very similar to numeric arrays in term of functionality but
they are different in terms of their index. Associative array will have their index as
string so that we can establish a strong association between key and values.

19

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• To store the salaries of employees in an array, a numerically indexed array would not
be the best choice. Instead, we could use the employees names as the keys in our
associative array, and the value would be their respective salary.
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array(
"mohammad" => 2000,
"qadir" => 1000,
"zara" => 500
);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */


$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body>
</html>

This will produce following result:


Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

Multidimensional Arrays
• A multi-dimensional array each element in the main array can also be an array. And
each element in the sub-array can be an array, and so on. Values in the multi-
dimensional array are accessed using multiple index.

• In this example we create a two dimensional array to store marks of three students in
three subjects:
<html>
<body>

20

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<?php
$marks = array(
"mohammad" => array
(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array
(
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array
(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>

This will produce following result:


Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

PHP - Strings
• Singly quoted strings are treated almost literally, whereas doubly quoted strings
replace variables with their values as well as specially interpreting certain character
sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);

21

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

print "<br />";


$literally = "My $variable will print!\\n";
print($literally);
?>

This will produce following result:


My $variable will not print!\n
My name will print
• There are no artificial limits on string length - within the bounds of available
memory, we ought to be able to make arbitrarily long strings.
• Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP:
• Certain character sequences beginning with backslash (\) are replaced with special
characters
• Variable names (starting with $) are replaced with string representations of their
values.
• The escape-sequence replacements are:
\n is replaced by the newline character
\r is replaced by the carriage-return character
\t is replaced by the tab character
\$ is replaced by the dollar sign itself ($)
\" is replaced by a single double-quote (")
\\ is replaced by a single backslash (\)
String Concatenation Operator
• To concatenate two string variables together, use the dot (.) operator:
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>

This will produce following result:


Hello World 1234
• If we look at the code above we see that we used the concatenation operator two
times. This is because we had to insert a third string.
• Between the two string variables we added a string with a single character, an empty
space, to separate the two variables.
Using the strlen() function
• The strlen() function is used to find the length of a string.
• Let's find the length of our string "Hello world!":
<?php
echo strlen("Hello world!");
?>

This will produce following result:


12

22

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• The length of a string is often used in loops or other functions, when it is important to
know when the string ends. (i.e. in a loop, we would want to stop the loop after the
last character in the string)
Using the strpos() function
• The strpos() function is used to search for a string or character within a string.
• If a match is found in the string, this function will return the position of the first
match. If no match is found, it will return FALSE.
• Let's see if we can find the string "world" in our string:
<?php
echo strpos("Hello world!","world");
?>

This will produce following result:


6
• As we see the position of the string "world" in our string is position 6. The reason that
it is 6, and not 7, is that the first position in the string is 0, and not 1.

PHP - Functions
• PHP functions are similar to other programming languages. A function is a piece of
code which takes one more input in the form of parameter and does some processing
and returns a value.
• We have seen many functions like fopen() and fread() etc. They are built-in functions
but PHP gives we option to create wer own functions as well.
• There are two parts which should be clear to we:
o Creating a PHP Function
o Calling a PHP Function
• Creating PHP Function
o Its very easy to create wer own PHP function. Suppose we want to create a
PHP function which will simply write a simple message on wer browser when
we will call it. Following example creates a function called writeMessage()
and then calls it just after creating it.
o Note that while creating a function its name should start with
keyword function and all the PHP code should be put inside { and } braces as
shown in the following example below:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>

<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "We are really a nice person, Have a nice time!";

23

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>

This will display following result:


We are really a nice person, Have a nice time!

PHP Functions with Parameters


• PHP gives we option to pass wer parameters inside a function. We can pass as many
as parameters wer like. These parameters work like variables inside function.
Following example takes two integer parameters and add them together and then print
them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>

This will display following result:


Sum of the two numbers is : 30

Passing Arguments by Reference


• It is possible to pass arguments to functions by reference. This means that a reference
to the variable is manipulated by the function rather than a copy of the variable's
value.
• Any changes made to an argument in these cases will change the value of the original
variable. We can pass an argument by reference by adding an ampersand to the
variable name in either the function call or the function definition.
• Following example depicts both the cases.

24

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{
$num += 5;
}

function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>

This will display following result:


Original Value is 10
Original Value is 16

PHP Functions retruning value


• A function can return a value using the return statement in conjunction with a value
or object. return stops the execution of the function and sends the value back to the
calling code.
• We can return more than one value from a function using return array(1,2,3,4).
• Following example takes two integer parameters and add them together and then
returns their sum to the calling program. Note that return keyword is used to return a
value from a function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;

25

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
</body>
</html>

This will display following result:


Returned value from the function : 30

Setting Default Values for Function Parameters


We can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function printMe($param = NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>

</body>
</html>

This will produce following result:


This is test

Dynamic Function Calls:


It is possible to assign function names as strings to variables and then treat these variables
exactly as we would the function name itself. Following example depicts this behaviour.
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello()
{

26

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

echo "Hello<br />";


}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>

This will display following result:


Hello

PHP - Cookies
• Cookies are text files stored on the client computer and they are kept of use tracking
purpose. PHP transparently supports HTTP cookies.
• There are three steps involved in identifying returning users:
• Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
• Browser stores this information on local machine for future use.
• When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
• This chapter will teach we how to set cookies, how to access them and how to delete
them.
• The Anatomyof a Cookie
• Cookies are usually set in an HTTP header (although JavaScript can also set a cookie
directly on a browser). A PHP script that sets a cookie might send headers that look
something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
• As we can see, the Set-Cookie header contains a name value pair, a GMT date, a path
and a domain. The name and value will be URL encoded. The expires field is an
instruction to the browser to "forget" the cookie after the given time and date.
• If the browser is configured to store cookies, it will then keep this information until
the expiry date. If the user points the browser at any page that matches the path and
domain of the cookie, it will resend the cookie to the server.The browser's headers
might look something like this:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*

27

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
• A PHP script will then have access to the cookie in the environmental variables
$_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values.
Above cookie can be accessed using $HTTP_COOKIE_VARS["name"].
Setting Cookies with PHP
• PHP provided setcookie() function to set a cookie. This function requires upto six
arguments and should be called before <html> tag. For each cookie this function has
to be called separately.
setcookie(name, value, expire, path, domain, security);

• Here is the detail of all the arguments:


• Name - This sets the name of the cookie and is stored in an environment variable
called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
• Value -This sets the value of the named variable and is the content that we actually
want to store.
• Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
After this time cookie will become inaccessible. If this parameter is not set then
cookie will automatically expire when the Web Browser is closed.
• Path -This specifies the directories for which the cookie is valid. A single forward
slash character permits the cookie to be valid for all directories.
• Domain - This can be used to specify the domain name in very large domains and
must contain at least two periods to be valid. All cookies are only valid for the host
and domain which created them.
• Security - This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by
regular HTTP.
• Following example will create two cookies name and age these cookies will be
expired after one hour.
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>
Accessing Cookies with PHP

28

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• PHP provides many ways to access cookies.Simplest way is to use either $_COOKIE
or $HTTP_COOKIE_VARS variables. Following example will access all the cookies
set in above example.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";

echo $_COOKIE["age"] . "<br />";


/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body>
</html>
We can use isset() function to check if a cookie is set or not.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>

Deleting Cookie with PHP


Officially, to delete a cookie we should call setcookie() with the name argument only but this
does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired:
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>

29

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>

PHP - Regular Expressions


• Regular expressions are nothing more than a sequence or pattern of characters itself.
They provide the foundation for pattern-matching functionality.
• Using regular expression we can search a particular string inside a another string, we
can replace one string by another string and we can split a string into many chunks.
• PHP offers functions specific to two sets of regular expression functions, each
corresponding to a certain type of regular expression. We can use any of them based
on comfort.
o POSIX Regular Expressions
o PERL Style Regular Expressions
o POSIX Regular Expressions
• The structure of a POSIX regular expression is not dissimilar to that of a typical
arithmetic expression: various elements (operators) are combined to form more
complex expressions.
• The simplest regular expression is one that matches a single character, such as g,
inside strings such as g, haggle, or bag.
• Lets give explaination for few concepts being used in POSIX regular expression.
After that we will introduce we wih regular expression related functions.
• Brackets
• Brackets ([]) have a special meaning when used in the context of regular expressions.
They are used to find a range of characters.
Expression Description
[0-9] It matches any decimal digit from 0 through 9.
[a-z] It matches any character from lowercase a through lowercase z.
[A-Z] It matches any character from uppercase A through uppercase Z.
[a-Z] It matches any character from lowercase a through uppercase Z.
• The ranges shown above are general; we could also use the range [0-3] to match any
decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase
character ranging from b through v.
• Quantifiers
The frequency or position of bracketed character sequences and single characters can be
denoted by a special character. Each pecial character having a specific connotation. The +, *, ?,
{int. range}, and $ flags all follow a character sequence.
Expression Description
p+ It matches any string containing at least one p.

30

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

p* It matches any string containing zero or more p's.


p? It matches any string containing zero or more p's. This is just an alternative way to us
p*.
p{N} It matches any string containing a sequence of N p's
p{2,3} It matches any string containing a sequence of two or three p's.
p{2, } It matches any string containing a sequence of at least two p's.
p$ It matches any string with p at the end of it.
^p It matches any string with p at the beginning of it.
Examples
Following examples will clear wer concepts about matching chracters.
Expression Description
[^a-zA-Z] It matches any string not containing any of the characters ranging from
a through z and A through Z.
p.p It matches any string containing p, followed by any character, in turn
followed by another p.
^.{2}$ It matches any string containing exactly two characters.
<b>(.*)</b> It matches any string enclosed within <b> and </b>.
p(hp)* It matches any string containing a p followed by zero or more instances
of the sequence hp.

Predefined Character Ranges


For programming convenience several predefined character ranges, also known as character
classes, are available. Character classes specify an entire range of characters, for example, the
alphabet or an integer set:
Expression Description
[[:alpha:]] It matches any string containing alphabetic characters aA through zZ.
[[:digit:]] It matches any string containing numerical digits 0 through 9.
[[:alnum:]] It matches any string containing alphanumeric characters aA through zZ
and 0 through 9.
[[:space:]] It matches any string containing a space.

PHP's Regexp POSIX Functions


PHP currently offers seven functions for searching strings using POSIX-style regular
expressions:
Function Description
ereg() The ereg() function searches a string specified by string for a string
specified by pattern, returning true if the pattern is found, and false
otherwise.
ereg_replace() The ereg_replace() function searches for string specified by pattern
and replaces pattern with replacement if found.
eregi() The eregi() function searches throughout a string specified by
pattern for a string specified by string. The search is not case sensitive.
eregi_replace() The eregi_replace() function operates exactly like ereg_replace(),
except that the search for pattern in string is not case sensitive.
split() The split() function will divide a string into various elements, the

31

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

boundaries of each element based on the occurrence of pattern in


string.
spliti() The spliti() function operates exactly in the same manner as its
sibling split(), except that it is not case sensitive.
sql_regcase() The sql_regcase() function can be thought of as a utility function,
converting each character in the input parameter string into a bracketed
expression containing two characters.

PHP's Regexp PERL Compatible Functions


PHP offers following functions for searching strings using Perl-compatible regular
expressions:
Function Description
preg_match() The preg_match() function searches string for pattern, returning
true if pattern exists, and false otherwise.
preg_match_all() The preg_match_all() function matches all occurrences of pattern
in string.
preg_replace() The preg_replace() function operates just like ereg_replace(),
except that regular expressions can be used in the pattern and
replacement input parameters.
preg_split() The preg_split() function operates exactly like split(), except that
regular expressions are accepted as input parameters for pattern.
preg_grep() The preg_grep() function searches all elements of input_array,
returning all elements matching the regexp pattern.
preg_ quote() Quote regular expression characters

PHP built in functions

PHP is very rich in terms of Buil-in functions. Here is the list of various important function
categories. There are various other function categories which are not covered here.
• PHP Array Functions
• PHP Calender Functions
• PHP Class/Object Functions
• PHP Character Functions
• PHP Date & Time Functions
• PHP Directory Functions
• PHP Error Handling Functions
• PHP File System Functions
• PHP MySQL Functions
• PHP Network Functions
• PHP ODBC Functions
• PHP String Functions
• PHP SimpleXML Functions
• PHP XML Parsing Functions

32

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

PHP Array Functions

Function Description
array() Create an array
array_change_key_case() Returns an array with all keys in lowercase or uppercase
array_chunk() Splits an array into chunks of arrays
array_combine() Creates an array by using one array for keys and another for its
values
array_count_values() Returns an array with the number of occurrences for each
value
array_diff() Compares array values, and returns the differences
array_diff_assoc() Compares array keys and values, and returns the differences
array_diff_key() Compares array keys, and returns the differences
array_diff_uassoc() Compares array keys and values, with an additional user-made
function check, and returns the differences
array_diff_ukey() Compares array keys, with an additional user-made function
check, and returns the differences
array_fill() Fills an array with values
array_fill_keys() Fill an array with values, specifying keys
array_filter() Filters elements of an array using a user-made function
array_flip() Exchanges all keys with their associated values in an array
array_intersect() Compares array values, and returns the matches
array_intersect_assoc() Compares array keys and values, and returns the matches
array_intersect_key() Compares array keys, and returns the matches
array_intersect_uassoc() Compares array keys and values, with an additional user-made
function check, and returns the matches
array_intersect_ukey() Compares array keys, with an additional user-made function
check, and returns the matches
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
array_map() Sends each value of an array to a user-made function, which
returns new values
array_merge() Merges one or more arrays into one array
array_merge_recursive() Merges one or more arrays into one array
array_multisort() Sorts multiple or multi-dimensional arrays
array_pad() Inserts a specified number of items, with a specified value, to
an array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
array_push() Inserts one or more elements to the end of an array
array_rand() Returns one or more random keys from an array
array_reduce() Returns an array as a string, using a user-defined function
array_reverse() Returns an array in the reverse order
array_search() Searches an array for a given value and returns the key
array_shift() Removes the first element from an array, and returns the value

33

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

of the removed element


array_slice() Returns selected parts of an array
array_splice() Removes and replaces specified elements of an array
array_sum() Returns the sum of the values in an array
array_udiff() Compares array values in a user-made function and returns an
array
array_udiff_assoc() Compares array keys, and compares array values in a user-
made function, and returns an array
array_udiff_uassoc() Compares array keys and array values in user-made functions,
and returns an array
array_uintersect() Compares array values in a user-made function and returns an
array
array_uintersect_assoc() Compares array keys, and compares array values in a user-
made function, and returns an array
array_uintersect_uassoc( Compares array keys and array values in user-made functions,
) and returns an array
array_unique() Removes duplicate values from an array
array_unshift() Adds one or more elements to the beginning of an array
array_values() Returns all the values of an array
array_walk() Applies a user function to every member of an array
array_walk_recursive() Applies a user function recursively to every member of an
array
arsort() Sorts an array in reverse order and maintain index association
asort() Sorts an array and maintain index association
compact() Create array containing variables and their values
count() Counts elements in an array, or properties in an object
current() Returns the current element in an array
each() Returns the current key and value pair from an array
end() Sets the internal pointer of an array to its last element
extract() Imports variables into the current symbol table from an array
in_array() Checks if a specified value exists in an array
key() Fetches a key from an array
krsort() Sorts an array by key in reverse order
ksort() Sorts an array by key
list() Assigns variables as if they were an array
natcasesort() Sorts an array using a case insensitive "natural order"
algorithm
natsort() Sorts an array using a "natural order" algorithm
next() Advance the internal array pointer of an array
pos() Alias of current()
prev() Rewinds the internal array pointer
range() Creates an array containing a range of elements
reset() Sets the internal pointer of an array to its first element
rsort() Sorts an array in reverse order
shuffle() Shuffles an array

34

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

sizeof() Alias of count()


sort() Sorts an array
uasort() Sorts an array with a user-defined function and maintain index
association
uksort() Sorts an array by keys using a user-defined function
usort() Sorts an array by values using a user-defined function

Calendar functions

Function Description
cal_days_in_month() Returns the number of days in a month for a specified year
and calendar
cal_from_jd() Converts a Julian day count into a date of a specified
calendar
cal_info() Returns information about a given calendar
cal_to_jd() Converts a date to Julian day count
easter_date() Returns the Unix timestamp for midnight on Easter of a
specified year
easter_days() Returns the number of days after March 21, on which Easter
falls for a specified year
FrenchToJD() Converts a French Republican date to a Julian day count
GregorianToJD() Converts a Gregorian date to a Julian day count
JDDayOfWeek() Returns the day of a week
JDMonthName() Returns a month name
JDToFrench() Converts a Julian day count to a French Republican date
JDToGregorian() Converts a Julian day count to a Gregorian date
jdtojewish() Converts a Julian day count to a Jewish date
JDToJulian() Converts a Julian day count to a Julian date
jdtounix() Converts a Julian day count to a Unix timestamp
JewishToJD() Converts a Jewish date to a Julian day count
JulianToJD() Converts a Julian date to a Julian day count
unixtojd() Converts a Unix timestamp to a Julian day count

Class and object function

Function Description
call_user_method_array() Call a user method given with an array of
parameters [deprecated]
call_user_method() Call a user method on an specific object
[deprecated]
class_exists() Checks if the class has been defined
get_class_methods() Gets the class methods' names
get_class_vars() Get the default properties of the class

35

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

get_class() Returns the name of the class of an object


get_declared_classes() Returns an array with the name of the defined
classes
get_declared_interfaces() Returns an array of all declared interfaces
get_object_vars() Gets the properties of the given object
get_parent_class() Retrieves the parent class name for object or class
interface_exists() Checks if the interface has been defined
is_a() Checks if the object is of this class or has this class
as one of its parents
is_subclass_of () Checks if the object has this class as one of its
parents
method_exists() Checks if the class method exists
property_exists() Checks if the object or class has a property

PHP- Character Functions

Function Description
ctype_alnum() Check for alphanumeric character(s)
ctype_alpha() Check for alphabetic character(s)
ctype_cntrl() Check for control character(s)
ctype_digit() Check for numeric character(s)
ctype_graph() Check for any printable character(s) except space
ctype_lower() Check for lowercase character(s)
ctype_print() Check for printable character(s)
ctype_punct() Check for any printable character which is not
whitespace or an alphanumeric character
ctype_space() Check for whitespace character(s)
ctype_upper() Check for uppercase character(s)
ctype_xdigit() Check for character(s) representing a hexadecimal
digit

PHP- Date & Time Functions

Function Description
checkdate() Validates a Gregorian date
date_create() Returns new DateTime object
date_date_set() Sets the date
date_default_timezone_get() Returns the default time zone
date_default_timezone_set() Sets the default time zone
date_format() Returns date formatted according to given
format
date_isodate_set() Sets the ISO date
date_modify() Alters the timestamp
date_offset_get() Returns the daylight saving time offset
date_parse() Returns associative array with detailed info

36

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

about given date


date_sun_info() Returns an array with information about
sunset/sunrise and twilight begin/end.
date_sunrise() Returns the time of sunrise for a given day /
location
date_sunset() Returns the time of sunset for a given day /
location
date_time_set() Sets the time
date_timezone_get() Return time zone relative to given DateTime
date_timezone_set() Sets the time zone for the DateTime object
date() Formats a local time/date
getdate() Returns an array that contains date and time
information for a Unix timestamp
gettimeofday() Returns an array that contains current time
information
gmdate() Formats a GMT/UTC date/time
gmmktime() Returns the Unix timestamp for a GMT date
gmstrftime() Formats a GMT/UTC time/date according to
locale settings
idate() Formats a local time/date as integer
localtime() Returns an array that contains the time
components of a Unix timestamp
microtime() Returns the microseconds for the current time
mktime() Returns the Unix timestamp for a date
strftime() Formats a local time/date according to locale
settings
strptime() Parses a time/date generated with strftime()
strtotime() Parses an English textual date or time into a
Unix timestamp
time() Returns the current time as a Unix timestamp
timezone_abbreviations_list() Returns associative array containing dst, offset
and the timezone name
timezone_identifiers_list() Returns numerically index array with all
timezone identifiers
timezone_name_from_abbr() Returns the timezone name from abbrevation
timezone_name_get() Returns the name of the timezone
timezone_offset_get() Returns the timezone offset from GMT
timezone_open() Returns new DateTimeZone object
timezone_transitions_get() Returns all transitions for the timezone

Directory functions

Function Description
chdir() Changes current directory
chroot() Change the root directory

37

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

dir() Opens a directory handle and returns an object.


closedir() Closes a directory
getcwd() Gets the current working directory.
opendir() Open directory handle
readdir() Read entry from directory handle
rewinddir() Rewind directory handle
scandir() List files and directories inside the specified path

PHP Database connection


Opening Database Connection
PHP provides mysql_connect function to open a database connection. This function takes
five parameters and returns a MySQL link identifier on success, or FALSE on failure.
Syntax
connection mysql_connect(server,user,passwd,new_link,client_flag);

Parameter Description
server Optional - The host name running database server. If not specified then
default value is localhost:3306.
user Optional - The username accessing the database. If not specified then
default is the name of the user that owns the server process.
passwd Optional - The password of the user accessing the database. If not
specified then default is an empty password.
new_link Optional - If a second call is made to mysql_connect() with the same
arguments, no new connection will be established; instead, the identifier of
the already opened connection will be returned.
client_flags Optional - A combination of the following constants:

MYSQL_CLIENT_SSL - Use SSL encryption


MYSQL_CLIENT_COMPRESS - Use compression protocol
MYSQL_CLIENT_IGNORE_SPACE - Allow space after function
names
MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout
seconds of inactivity before closing the connection
.
Closing Database Connection
Its simplest function mysql_close PHP provides to close a database connection. This function
takes connection resource returned by mysql_connect function. It returns TRUE on success or
FALSE on failure.
Syntax
bool mysql_close ( resource $link_identifier );
If a resource is not specified then last opend database is closed.

38

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Try out following example to open and close a database connection:


<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
Create MySQL Database Using PHP
Creating a Database
To create and delete a database we should have admin priviledge. Its very easy to create a
new MySQL database. PHP uses mysql_query function to create a MySQL database. This
function takes two parameters and returns TRUE on success or FALSE on failure.
Syntax
bool mysql_query( sql, connection );

Parameter Description
sql Required - SQL query to create a database
connection Optional - if not specified then last opend connection by mysql_connect
will be used.

Try out following example to create a database:

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'CREATE Database test_db';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create database: ' . mysql_error());

39

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

}
echo "Database test_db created successfully\n";
mysql_close($conn);
?>

Selecting a Database
Once we estblish a connection with a database server then it is required to select a particular
database where wer all the tables are associated.
This is required because there may be multiple databases residing on a single server and we
can do work with a single database at a time.
PHP provides function mysql_select_db to select a database.It returns TRUE on success or
FALSE on failure.
Syntax
bool mysql_select_db( db_name, connection );

Parameter Description
db_name Required - Database name to be selected
connection Optional - if not specified then last opend connection by mysql_connect
will be used.

Here is the example showing we how to select a database.


<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db( 'test_db' );
mysql_close($conn);
?>
Creating Database Tables
To create tables in the new database we need to do the same thing as creating the database.
First create the SQL query to create the tables then execute the query using mysql_query()
function.
Try out following example to create a table:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

40

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'CREATE TABLE employee( '.
'emp_id INT NOT NULL AUTO_INCREMENT, '.
'emp_name VARCHAR(20) NOT NULL, '.
'emp_address VARCHAR(20) NOT NULL, '.
'emp_salary INT NOT NULL, '.
'join_date timestamp(14) NOT NULL, '.
'primary key ( emp_id ))';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table employee created successfully\n";
mysql_close($conn);
?>

Deleting a Database
If a database is no longer required then it can be deleted forever. We can use pass an SQL
command to mysql_query to delete a database.
Try out following example to drop a database.

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'DROP DATABASE test_db';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete database db_test: ' . mysql_error());
}
echo "Database deleted successfully\n";
mysql_close($conn);
?>

41

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Deleting a Table
Its again a matter of issuing one SQL command through mysql_query function to delete any
database table. But be very careful while using this command because by doing so we can delete
some important information we have in wer table.
Try out following example to drop a table:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'DROP TABLE employee';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete table employee: ' . mysql_error());
}
echo "Table deleted successfully\n";
mysql_close($conn);
?>
Insert Data into MySQL Database
Data can be entered into MySQL tables by executing SQL INSERT statement through PHP
function mysql_query. Below a simle example to insert a record into employee table.
Try out following example to insert record into employee table.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO employee '.
'(emp_name,emp_address, emp_salary, join_date) '.
'VALUES ( "guest", "XYZ", 2000, NOW() )';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());

42

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

}
echo "Entered data successfully\n";
mysql_close($conn);
?>

Getting Data From MySQL Database


Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP
function mysql_query. We have several options to fetch data from MySQL.
The most frequently used option is to use function mysql_fetch_array(). This function
returns row as an associative array, a numeric array, or both. This function returns FALSE if
there are no more rows.
Below is a simple example to fetch records from employee table.

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "EMP ID :{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".
"EMP SALARY : {$row['emp_salary']} <br> ".
" ------------------------------- <br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>

Using Paging through PHP


Its always possible that wer SQL SELECT statement query may result into thousand of
records. But its is not good idea to display all the results on one page. So we can divide this
result into many pages as per requirement.

43

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Paging means showing wer query result in multiple pages instead of just put them all in one
long page.
MySQL helps to generate paging by using LIMIT clause which will take two arguments.
First argument as OFFSET and second argument how many records should be returned from the
database.
Below is a simple example to fetch records using LIMIT clause to generate paging.
Try out following example to display 10 records per page.
<html>
<head>
<title>Paging Using PHP</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$rec_limit = 10;

$conn = mysql_connect($dbhost, $dbuser, $dbpass);


if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('test_db');
/* Get total number of records */
$sql = "SELECT count(emp_id) FROM employee ";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
$rec_count = $row[0];

if( isset($_GET{'page'} ) )
{
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
}
else
{
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);

44

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

$sql = "SELECT emp_id, emp_name, emp_salary ".


"FROM employee ".
"LIMIT $offset, $rec_limit";

$retval = mysql_query( $sql, $conn );


if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "EMP ID :{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".
"EMP SALARY : {$row['emp_salary']} <br> ".
" ------------------------------- <br>";
}

if( $page > 0 )


{
$last = $page - 2;
echo "<a href=\"$_PHP_SELF?page=$last\">Last 10 Records</a> |";
echo "<a href=\"$_PHP_SELF?page=$page\">Next 10 Records</a>";
}
else if( $page == 0 )
{
echo "<a href=\"$_PHP_SELF?page=$page\">Next 10 Records</a>";
}
else if( $left_rec < $rec_limit )
{
$last = $page - 2;
echo "<a href=\"$_PHP_SELF?page=$last\">Last 10 Records</a>";
}
mysql_close($conn);
?>

Updating Data into MySQL Database


Data can be updated into MySQL tables by executing SQL UPDATE statement through PHP
function mysql_query.
Below is a simple example to update records into employee table. To update a record in any
table it is required to locate that record by using a conditional clause. Below example uses
primary key to match a record in employee table.
Try out following example to understand update operation. We need to provide an
employee ID to update an employee salary.
<html>
<head>
<title>Update a Record in MySQL Database</title>

45

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

</head>
<body>

<?php
if(isset($_POST['update']))
{
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}

$emp_id = $_POST['emp_id'];
$emp_salary = $_POST['emp_salary'];

$sql = "UPDATE employee ".


"SET emp_salary = $emp_salary ".
"WHERE emp_id = $emp_id" ;

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Employee ID</td>
<td><input name="emp_id" type="text" id="emp_id"></td>
</tr>
<tr>
<td width="100">Employee Salary</td>
<td><input name="emp_salary" type="text" id="emp_salary"></td>
</tr>
<tr>
<td width="100"> </td>

46

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>

Deleting Data from MySQL Database


Data can be deleted from MySQL tables by executing SQL DELETE statement through PHP
function mysql_query.
Below is a simple example to delete records into employee table. To delete a record in any
table it is required to locate that record by using a conditional clause. Below example uses
primary key to match a record in employee table.
Try out following example to understand delete operation. We need to provide an
employee ID to delete an employee record from employee table.
<html>
<head>
<title>Delete a Record from MySQL Database</title>
</head>
<body>

<?php
if(isset($_POST['delete']))
{
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}

$emp_id = $_POST['emp_id'];

$sql = "DELETE employee ".


"WHERE emp_id = $emp_id" ;

47

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Employee ID</td>
<td><input name="emp_id" type="text" id="emp_id"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="delete" type="submit" id="delete" value="Delete">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>

48

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Introduction to XML

1. XML was designed to describe data and focus on what data is.
2. HTML was designed to display data and focus on how data looks.
What is XML?
1. XML stands for EXtensible Markup Language
2. XML is a markup language much like HTML
3. XML was designed to describe data
4. XML tags are not predefined. You must define your own tags
5. XML uses a Document Type Definition (DTD) or an XML Schema to describe the data
6. XML with a DTD or XML Schema is designed to be self-descriptive
The main difference between XML and HTML
1. XML was designed to carry data.
2. XML was designed to describe data and to focus on what data is.
3. HTML was designed to display data and to focus on how data looks.
4. HTML is about displaying information, while XML is about describing information.
5. XML was created to structure, store and to send information.
The following example is a note to Tove from Jani, stored as XML:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
The note has a header and a message body. It also has sender and receiver information. But
still, this XML document does not DO anything. It is just pure information wrapped in XML
tags. Someone must write a piece of software to send, receive or display it.
6. XML is free and extensible
Features of XML
1. XML tags are not predefined. You must "invent" your own tags.
2. XML is not a replacement for HTML.
3. XML is a cross-platform, software and hardware independent tool for transmitting
information.
4. XML is going to be everywhere.
How can XML be Used?
• XML was designed to store, carry, and exchange data.
• XML was not designed to display data.
• XML can Separate Data from HTML
• With XML, your data is stored outside your HTML.
• XML data can also be stored inside HTML pages as "Data Islands".
• With XML, data can be exchanged between incompatible systems.
• Converting the data to XML can greatly reduce this complexity and create
data that can be read by many different types of applications.
• With XML, financial information can be exchanged over the Internet.

49

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• Expect to see a lot about XML and B2B (Business To Business) in the near
future.
• With XML, plain text files can be used to share data.
• With XML, plain text files can be used to store data.
• XML can also be used to store data in files or in databases. Applications can
be written to store and retrieve information from the store, and generic
applications can be used to display the data.
• With XML, your data is available to more users.
• Since XML is independent of hardware, software and application, you can
make your data available to other than only standard HTML browsers.
• XML is the mother of WAP and WML.
• The Wireless Markup Language (WML), used to markup Internet applications
for handheld devices like mobile phones, is written in XML
XML Syntax

XML documents use a self-describing and simple syntax.


<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
• The first line in the document - the XML declaration - defines the XML version and the
character encoding used in the document. In this case the document conforms to the 1.0
specification of XML and uses the ISO-8859-1 (Latin-1/West European) character set.
• The next line describes the root element of the document (like it was saying: "this
document is a note"):
<note>
• The next 4 lines describe 4 child elements of the root (to, from, heading, and body):
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
• And finally the last line defines the end of the root element:
</note>
Rules followed in an XML document
1. With XML, it is illegal to omit the closing tag.
2. .XML tags are case sensitive
3. All XML elements must be properly nested
4. All XML documents must have a root element
5. All XML documents must contain a single tag pair to define a root element.
6. All other elements must be within this root element.
7. All elements can have sub elements (child elements). Sub elements must be correctly
nested within their parent element:
<root>

50

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<child>
<subchild> .....</subchild>
</child>
</root>
8. Attribute values must always be quoted
<?xml version="1.0" encoding="ISO-8859-1"?>
<note date="12/11/2002">
<to>Tove</to>
<from>Jani</from>
</note>
9. With XML, white space is preserved
10. With XML, CR / LF is converted to LF
11. The syntax for writing comments in XML is similar to that of HTML.
12. <!-- This is a comment -->
13. In an XML-aware application however, the XML tags can be handled specially. The tags
may or may not be visible, or have a functional meaning, depending on the nature of the
application.
14. XML Elements are extensible and they have relationships.
15. XML Elements have simple naming rules.
16. XML Elements are Extensible
17. XML documents can be extended to carry more information.
18. Look at the following XML NOTE example:
<note>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>
19. Let's imagine that we created an application that extracted the <to>, <from>, and <body>
elements from the XML document to produce this output:
MESSAGE
To: Tove
From: Jani
Don't forget me this weekend!
20. Imagine that the author of the XML document added some extra information to it:
<note>
<date>2002-08-01</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
22. XML Elements have Relationships
23. Elements are related as parents and children.
Imagine that this XML document describes the book:
<book>
<title>My First XML</title>

51

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<prod id="33-657" media="paper"></prod>


<chapter>Introduction to XML
<para>What is HTML</para>
<para>What is XML</para>
</chapter>
<chapter>XML Syntax
<para>Elements must have a closing tag</para>
<para>Elements must be properly nested</para>
</chapter>
</book>
23. Book is the root element. Title, prod, and chapter are child elements of book. Book is
the parent element of title, prod, and chapter. Title, prod, and chapter are siblings (or sister
elements) because they have the same parent.
24. Elements have Content
25. Elements can have different content types.
26. An XML element is everything from (including) the element's start tag to (including) the
element's end tag.
27. An element can have element content, mixed content, simple content, or empty content.
An element can also have attributes.
28. In the example above, book has element content, because it contains other elements.
Chapter has mixed content because it contains both text and other elements. Para has simple
content (or text content) because it contains only text. Prod has empty content, because it
carries no information.
29. In the example above only the prod element has attributes. The attribute named id has
the value "33-657". The attribute named media has the value "paper".
30. XML elements must follow these naming rules:
• Names can contain letters, numbers, and other characters
• Names must not start with a number or punctuation character
• Names must not start with the letters xml (or XML or Xml ..)
• Names cannot contain spaces
31. XML Attributes
1. XML elements can have attributes in the start tag, just like HTML.
2. Attributes are used to provide additional information about elements.
In HTML (and in XML) attributes provide additional information about elements:
<img src="computer.gif">
<a href="demo.asp">
Attributes often provide information that is not a part of the data
Quote Styles, "female" or 'female'?
Attribute values must always be enclosed in quotes, but either single or double quotes can be
used. For a person's sex, the person tag can be written like this:
<person sex="female">
or like this: <person sex='female'>
33. Data can be stored in child elements or in attributes.
Take a look at these examples:
<person sex="female">
<firstname>Anna</firstname>

52

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<lastname>Smith</lastname>
</person>
In the first example sex is an attribute. In the last, sex is a child element. Both examples
provide the same information.
There are no rules about when to use attributes, and when to use child elements. My
experience is that attributes are handy in HTML, but in XML you should try to avoid them. Use
child elements if the information feels like data.
34. I like to store data in child elements.
The following three XML documents contain exactly the same information:
36. attributes cannot contain multiple values (child elements can)
37. attributes are not easily expandable (for future changes)
38. attributes cannot describe structures (child elements can)
39. attributes are more difficult to manipulate by program code
40. attribute values are not easy to test against a Document Type Definition
41. (DTD) - which is used to define the legal elements of an XML document
42. Sometimes I assign ID references to elements. These ID references can be used to
access XML elements in much the same way as the NAME or ID attributes in HTML.
This example demonstrates this:
<messages>
<note id="p501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="p502">
<to>Jani</to>
<from>Tove</from>
<heading>Re: Reminder</heading>
<body>I will not!</body>
</note>
</messages>
44. The ID in these examples is just a counter, or a unique identifier, to identify the different
notes in the XML file, and not a part of the note data.

Introduction to DTD
The purpose of a Document Type Definition is to define the legal building blocks of an XML
document. It defines the document structure with a list of legal elements.
Internal DOCTYPE declaration

If the DTD is included in your XML source file, it should be wrapped in a DOCTYPE
definition with the following syntax:
<!DOCTYPE root-element [element-declarations]>

Example XML document with a DTD


<?xml version="1.0"?>

53

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend</body>
</note>
External DOCTYPE declaration

If the DTD is external to your XML source file, it should be wrapped in a DOCTYPE
definition with the following syntax:
<!DOCTYPE root-element SYSTEM "filename">

This is the same XML document as above, but with an external DTD:
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

"note.dtd" containing the DTD:


<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
DTD - XML building blocks
The main building blocks of both XML and HTML documents are tags like
<body> ... </body>.
The building blocks of XML documents

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

Elements
Tags
Attributes

54

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Entities
PCDATA
CDATA

The following is a brief explanation of each of the building blocks:


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".
Tags

Tags are used to markup elements.

A starting tag like <element_name> marks up the beginning of an element, and an ending tag
like </element_name> marks up the end of an element.
Attributes

Attributes provide extra information about elements.

Attributes are always placed inside the starting 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

Entities are variables used to define common text. Entity references are references to
entities.

The following entities are predefined in XML:


Entity References Character
&lt; <
&gt; >
&amp; &
&quot; "
&apos; '

PCDATA

PCDATA means parsed character data.

55

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

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

CDATA also 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.
DTD - Elements
In a DTD, XML elements are declared with a DTD element declaration.
Declaring an Element

In the DTD, XML elements are declared with an element declaration. An element declaration
has the following syntax:
<!ELEMENT element-name category>
or
<!ELEMENT element-name (element-content)>

Empty elements

Empty elements are declared with the category keyword EMPTY:


<!ELEMENT element-name EMPTY>

example:
<!ELEMENT br EMPTY>
XML example:
<br />

Elements with only character data

Elements with only character data are declared with #PCDATA inside parentheses:
<!ELEMENT element-name (#PCDATA)>

example:
<!ELEMENT from (#PCDATA)>

Elements with any contents

Elements declared with the category keyword ANY, can contain any combination of parsable
data:
<!ELEMENT element-name ANY>
example:
<!ELEMENT note ANY>

Elements with children (sequences)

56

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Elements with one or more children are defined with the name of the children elements
inside parentheses:
<!ELEMENT element-name
(child-element-name)>
or
<!ELEMENT element-name
(child-element-name,child-element-name,. ...... )>
example:
<!ELEMENT note (to,from,heading,body)>

When children are declared in a sequence separated by commas, the children must appear in
the same sequence in the document. In a full declaration, the children must also be declared, and
the children can also have children. The full declaration of the "note" element will be:
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

Declaring only one occurrence of the same element


<!ELEMENT element-name (child-name)>
example:
<!ELEMENT note (message)>

The example declaration above declares that the child element message must occur once, and
only once inside the "note" element.
Declaring minimum one occurrence of the same element
<!ELEMENT element-name (child-name+)>
example:
<!ELEMENT note (message+)>

The + sign in the example above declares that the child element message must occur one or
more times inside the "note" element.
Declaring zero or more occurrences of the same element
<!ELEMENT element-name (child-name*)>
example:
<!ELEMENT note (message*)>

The * sign in the example above declares that the child element message can occur zero or
more times inside the "note" element.
Declaring zero or one occurrences of the same element
<!ELEMENT element-name (child-name?)>
example:
<!ELEMENT note (message?)>

57

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The ? sign in the example above declares that the child element message can occur zero or
one times inside the "note" element.
Declaring either/or content
example:
<!ELEMENT note (to,from,header,(message|body))>

The example above declares that the "note" element must contain a "to" element, a "from"
element, a "header" element, and either a "message" or a "body" element.
Declaring mixed content
example:
<!ELEMENT note (#PCDATA|to|from|header|message)*>

The example above declares that the "note" element can contain zero or more occurrences of
parsed character, "to", "from", "header
DTD - Attributes
In a DTD, Attributes are declared with an ATTLIST declaration.
Declaring Attributes

An attribute declaration has the following syntax:


<!ATTLIST element-name attribute-name
attribute-type default-value>
example:
DTD example:
<!ATTLIST payment type CDATA "check">

XML example:
<payment type="check" />

The attribute-type can have the following values:


Value Explanation
CDATA The value is character data
(en1|en2|..) The value must be one from an enumerated list
ID The value is a unique id
IDREF The value is the id of another element
IDREFS The value is a list of other ids
NMTOKEN The value is a valid XML name
NMTOKENS The value is a list of valid XML names
ENTITY The value is an entity
ENTITIES The value is a list of entities
NOTATION The value is a name of a notation
xml: The value is a predefined xml value

The default-value can have the following values:

58

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Value Explanation
value The default value of the attribute
#REQUIRED The attribute value must be included in the element
#IMPLIED The attribute does not have to be included
#FIXED value The attribute value is fixed

Specifying a Default attribute value


DTD:
<!ELEMENT square EMPTY>
<!ATTLIST square width CDATA "0">
Valid XML:
<square width="100" />

In the example above, the "square" element is defined to be an empty element with a "width"
attribute of type CDATA. If no width is specified, it has a default value of 0.
#IMPLIED
Syntax
<!ATTLIST element-name attribute-name
attribute-type #IMPLIED>
Example
DTD:
<!ATTLIST contact fax CDATA #IMPLIED>
Valid XML:
<contact fax="555-667788" />
Valid XML:
<contact />

Use the #IMPLIED keyword if you don't want to force the author to include an attribute, and
you don't have an option for a default value.
#REQUIRED
Syntax
<!ATTLIST element-name attribute_name
attribute-type #REQUIRED>
Example
DTD:
<!ATTLIST person number CDATA #REQUIRED>
Valid XML:
<person number="5677" />
Invalid XML:
<person />

Use the #REQUIRED keyword if you don't have an option for a default value, but still want
to force the attribute to be present.
#FIXED
Syntax

59

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<!ATTLIST element-name attribute-name


attribute-type #FIXED "value">
Example
DTD:
<!ATTLIST sender company CDATA #FIXED "Microsoft">
Valid XML:
<sender company="Microsoft" />
Invalid XML:
<sender company="W3Schools" />

Use the #FIXED keyword when you want an attribute to have a fixed value without allowing
the author to change it. If an author includes another value, the XML parser will return an error.

Enumerated attribute values


Syntax:
<!ATTLIST element-name
attribute-name (en1|en2|..) default-value>
DTD example:
<!ATTLIST payment type (check|cash) "cash">

XML example:
<payment type="check" />
or
<payment type="cash" />

Use enumerated attribute values when you want the attribute values to be one of a fixed set
of legal values.
DTD - Entities
• Entities are variables used to define shortcuts to common text.
• Entity references are references to entities.
• Entities can be declared internal, or external
Internal Entity Declaration
Syntax:
<!ENTITY entity-name "entity-value">

DTD Example:
<!ENTITY writer "Donald Duck.">
<!ENTITY copyright "Copyright W3Schools.">
XML example:
<author>&writer;&copyright;</author>

External Entity Declaration


Syntax:
<!ENTITY entity-name SYSTEM "URI/URL">

60

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

DTD Example:
<!ENTITY writer
SYSTEM "http://www.w3schools.com/entities/entities.xml">
<!ENTITY copyright
SYSTEM "http://www.w3schools.com/entities/entities.dtd">
XML example:
<author>&writer;&copyright;</author>
DTD Validation
Internet Explorer 5.0 can validate your XML against a DTD.
Validating with the XML Parser

If you try to open an XML document, the XML Parser might generate an error. By accessing
the parseError object, the exact error code, the error text, and even the line that caused the error
can be retrieved:

Note: The load( ) method is used for files, while the loadXML( ) method is used for strings.
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.validateOnParse="true"
xmlDoc.load("note_dtd_error.xml")

document.write("<br>Error Code: ")


document.write(xmlDoc.parseError.errorCode)
document.write("<br>Error Reason: ")
document.write(xmlDoc.parseError.reason)
document.write("<br>Error Line: ")
document.write(xmlDoc.parseError.line)
Turning Validation off

Validation can be turned off by setting the XML parser's validateOnParse="false".


var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.validateOnParse="false"
xmlDoc.load("note_dtd_error.xml")

document.write("<br>Error Code: ")


document.write(xmlDoc.parseError.errorCode)
document.write("<br>Error Reason: ")
document.write(xmlDoc.parseError.reason)
document.write("<br>Error Line: ")
document.write(xmlDoc.parseError.line)

DTD - Examples -TV Schedule DTD

61

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<!DOCTYPE TVSCHEDULE [
<!ELEMENT TVSCHEDULE (CHANNEL+)>
<!ELEMENT CHANNEL (BANNER,DAY+)>
<!ELEMENT BANNER (#PCDATA)>
<!ELEMENT DAY (DATE,(HOLIDAY|PROGRAMSLOT+))+>
<!ELEMENT HOLIDAY (#PCDATA)>
<!ELEMENT DATE (#PCDATA)>
<!ELEMENT PROGRAMSLOT (TIME,TITLE,DESCRIPTION?)>
<!ELEMENT TIME (#PCDATA)>
<!ELEMENT TITLE (#PCDATA)>
<!ELEMENT DESCRIPTION (#PCDATA)>

<!ATTLIST TVSCHEDULE NAME CDATA #REQUIRED>


<!ATTLIST CHANNEL CHAN CDATA #REQUIRED>
<!ATTLIST PROGRAMSLOT VTR CDATA #IMPLIED>
<!ATTLIST TITLE RATING CDATA #IMPLIED>
<!ATTLIST TITLE LANGUAGE CDATA #IMPLIED>

]>

Newspaper Article DTD


<!DOCTYPE NEWSPAPER [
<!ELEMENT NEWSPAPER (ARTICLE+)>
<!ELEMENT ARTICLE (HEADLINE,BYLINE,LEAD,BODY,NOTES)>
<!ELEMENT HEADLINE (#PCDATA)>
<!ELEMENT BYLINE (#PCDATA)>
<!ELEMENT LEAD (#PCDATA)>
<!ELEMENT BODY (#PCDATA)>
<!ELEMENT NOTES (#PCDATA)>
<!ATTLIST ARTICLE AUTHOR CDATA #REQUIRED>
<!ATTLIST ARTICLE EDITOR CDATA #IMPLIED>
<!ATTLIST ARTICLE DATE CDATA #IMPLIED>
<!ATTLIST ARTICLE EDITION CDATA #IMPLIED>
<!ENTITY NEWSPAPER "Vervet Logic Times">
<!ENTITY PUBLISHER "Vervet Logic Press">
<!ENTITY COPYRIGHT "Copyright 1998 Vervet Logic Press">
]>

Product Catalog DTD


<!DOCTYPE CATALOG [
<!ENTITY AUTHOR "John Doe">
<!ENTITY COMPANY "JD Power Tools, Inc.">
<!ENTITY EMAIL "[email protected]">

<!ELEMENT CATALOG (PRODUCT+)>

62

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<!ELEMENT PRODUCT
(SPECIFICATIONS+,OPTIONS?,PRICE+,NOTES?)>
<!ATTLIST PRODUCT
NAME CDATA #IMPLIED
CATEGORY (HandTool|Table|Shop-Professional) "HandTool"
PARTNUM CDATA #IMPLIED
PLANT (Pittsburgh|Milwaukee|Chicago) "Chicago"
INVENTORY (InStock|Backordered|Discontinued) "InStock">

<!ELEMENT SPECIFICATIONS (#PCDATA)>


<!ATTLIST SPECIFICATIONS
WEIGHT CDATA #IMPLIED
POWER CDATA #IMPLIED>

<!ELEMENT OPTIONS (#PCDATA)>


<!ATTLIST OPTIONS
FINISH (Metal|Polished|Matte) "Matte"
ADAPTER (Included|Optional|NotApplicable) "Included"
CASE (HardShell|Soft|NotApplicable) "HardShell">

<!ELEMENT PRICE (#PCDATA)>


<!ATTLIST PRICE
MSRP CDATA #IMPLIED
WHOLESALE CDATA #IMPLIED
STREET CDATA #IMPLIED
SHIPPING CDATA #IMPLIED>

<!ELEMENT NOTES (#PCDATA)>

]>

Introduction to XML Schema

• XML Schema is an XML based alternative to DTD.


• An XML schema describes the structure of an XML document.
• The XML Schema language is also referred to as XML Schema Definition (XSD).
• XML Schemas are richer and more useful than DTDs
• XML Schemas are written in XML
• XML Schemas support data types
• XML Schemas support namespaces

An XML Schema:
1. defines elements that can appear in a document
2. defines attributes that can appear in a document

63

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

3. defines which elements are child elements


4. defines the order of child elements
5. defines the number of child elements
6. defines whether an element is empty or can include text
7. defines data types for elements and attributes
8. defines default and fixed values for elements and attributes
XML Schema has Support for Data Types
One of the greatest strength of XML Schemas is the support for data types.
With the support for data types:
1. It is easier to describe permissible document content
2. It is easier to validate the correctness of data
3. It is easier to work with data from a database
4. It is easier to define data facets (restrictions on data)
5. It is easier to define data patterns (data formats)
6. It is easier to convert data between different data types

A Simple XML Document


Look at this simple XML document called "note.xml":
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

A Simple DTD
This is a simple DTD file called "note.dtd" that defines the elements of the XML document
above ("note.xml"):
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
A Simple XML Schema
This is a simple XML Schema file called "note.xsd" that defines the elements of the XML
document above ("note.xml"):
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>

64

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<xs:element name="from" type="xs:string"/>


<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The note element is said to be of a complex type because it contains other elements. The
other elements (to, from, heading, body) are said to be simple types because they do not contain
other elements.

XSD - The <schema> Element


The <schema> element is the root element of every XML Schema!
The <schema> Element
The <schema> element is the root element of every XML Schema:
<?xml version="1.0"?>
<xs:schema>
...
...
</xs:schema>
The <schema> element may contain some attributes. A schema declaration often looks
something like this:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">
...
...
</xs:schema>
Referencing a Schema in an XML Document
This XML document has a reference to an XML Schema:
<?xml version="1.0"?>
<note xmlns="http://www.w3schools.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3schools.com note.xsd">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XSD Simple Elements
A simple element is an XML element that can contain only text. It cannot contain any other
elements or attributes.

The syntax for defining a simple element is:


<xs:element name="xxx" type="yyy"/>
65

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

where xxx is the name of the element and yyy is the data type of the element.
Common XML Schema Data Types
XML Schema has a lot of built-in data types. Here is a list of the most common types:
xs:string
xs:decimal
xs:integer
xs:boolean
xs:date
xs:time
XSD Attributes
Simple elements cannot have attributes. If an element has attributes, it is considered to be of
complex type. But the attribute itself is always declared as a simple type. This means that an
element with attributes always has a complex type definition.
The syntax for defining an attribute is:
<xs:attribute name="xxx" type="yyy"/>

where xxx is the name of the attribute and yyy is the data type of the attribute.
Here are an XML element with an attribute:

Restrictions on Content
When an XML element or attribute has a type defined, it puts a restriction for the element's
or attribute's content. If an XML element is of type "xs:date" and contains a string like "Hello
Mother", the element will not validate.
But, there is more... with XML Schemas, you can add your own restrictions to your XML
elements and attributes. These restrictions are called facets.
XSD Restrictions/Facets

This example defines an element called "age" with a restriction. The value of age can
NOT be lower than 0 or greater than 100:
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="100"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

Restrictions for Datatypes


Constraint Description
enumeration Defines a list of acceptable values
fractionDigits Specifies the maximum number of decimal places allowed. Must be equal to
or greater than zero
length Specifies the exact number of characters or list items allowed. Must be equal
to or greater than zero

66

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

maxExclusive Specifies the upper bounds for numeric values (the value must be less than
this value)
maxInclusive Specifies the upper bounds for numeric values (the value must be less than or
equal to this value)
maxLength Specifies the maximum number of characters or list items allowed. Must be
equal to or greater than zero
minExclusive Specifies the lower bounds for numeric values (the value must be greater
than this value)
minInclusive Specifies the lower bounds for numeric values (the value must be greater
than or equal to this value)
minLength Specifies the minimum number of characters or list items allowed. Must be
equal to or greater than zero
pattern Defines the exact sequence of characters that are acceptable
totalDigits Specifies the exact number of digits allowed. Must be greater than zero
whiteSpace Specifies how white space (line feeds, tabs, spaces, and carriage returns) are
handled

XSD Complex Elements

1. A complex element is an XML element that contains other elements and/or attributes.
2. There are four kinds of complex elements:
• empty elements
• elements that contain only other elements
• elements that contain only text
• elements that contain both other elements and text
Examples of Complex XML Elements
A complex XML element, "product", which is empty:
<product pid="1345"/>
We can define a complex element in an XML Schema in different ways:.
1. The "employee" element can be declared directly by naming the element, like this:
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

If we use the method described above, several elements can refer to the same complex type,
like this:

67

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<xs:element name="employee" type="personinfo"/>


<xs:element name="student" type="personinfo"/>
<xs:element name="member" type="personinfo"/>

<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>

we can also base a complex element on an existing complex element and add some elements,
like this:
<xs:element name="employee" type="fullpersoninfo"/>

<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="fullpersoninfo">
<xs:complexContent>
<xs:extension base="personinfo">
<xs:sequence>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>

Complex Empty Elements

The "product" element above has no content at all. To define a type with no content, we must
define a type that allows elements in its content, but we do not actually declare any elements,
like this:
<xs:element name="product">
<xs:complexType>
<xs:complexContent>
<xs:restriction base="xs:integer">
<xs:attribute name="prodid" type="xs:positiveInteger"/>
</xs:restriction>
</xs:complexContent>

68

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

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

However, it is possible to declare the "product" element more compactly, like this:
<xs:element name="product">
<xs:complexType>
<xs:attribute name="prodid" type="xs:positiveInteger"/>
</xs:complexType>
</xs:element>

Or you can give the complexType element a name, and let the "product" element have a type
attribute that refers to the name of the complexType (if you use this method, several elements
can refer to the same complex type):
<xs:element name="product" type="prodtype"/>

<xs:complexType name="prodtype">
<xs:attribute name="prodid" type="xs:positiveInteger"/>
</xs:complexType>
Complex Types Containing Elements Only

An XML element, "person", that contains only other elements:


<person>
<firstname>John</firstname>
<lastname>Smith</lastname>
</person>

We can define the "person" element in a schema, like this:


<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

Complex Text-Only Elements

This type contains only simple content (text and attributes), therefore we add a
simpleContent element around the content. When using simple content, you must define an
extension OR a restriction within the simpleContent element, like this:
<xs:element name="somename">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="basetype">
....

69

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

....
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>

OR

<xs:element name="somename">
<xs:complexType>
<xs:simpleContent>
<xs:restriction base="basetype">
....
....
</xs:restriction>
</xs:simpleContent>
</xs:complexType>
</xs:element>

The following example declares a complexType, "shoesize". The content is defined as an


integer value, and the "shoesize" element also contains an attribute named "country":
<xs:element name="shoesize">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:integer">
<xs:attribute name="country" type="xs:string" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>

XSD Mixed Content


A mixed complex type element can contain attributes, elements, and text.

Complex Types with Mixed Content

An XML element, "letter", that contains both text and other elements:
<letter>
Dear Mr.<name>John Smith</name>.
Your order <orderid>1032</orderid>
will be shipped on <shipdate>2001-07-13</shipdate>.
</letter>

The following schema declares the "letter" element:


<xs:element name="letter">
<xs:complexType mixed="true">

70

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="orderid" type="xs:positiveInteger"/>
<xs:element name="shipdate" type="xs:date"/>
</xs:sequence>
</xs:complexType>
</xs:element>
XSD Indicators

We can control HOW elements are to be used in documents with indicators.

Indicators

There are seven indicators:

Order indicators:

• All
• Choice
• Sequence

Occurrence indicators:

• maxOccurs
• minOccurs

Group indicators:

• Group name
• attributeGroup name
Order Indicators

Order indicators are used to define the order of the elements.


All Indicator

The <all> indicator specifies that the child elements can appear in any order, and that each
child element must occur only once:
<xs:element name="person">
<xs:complexType>
<xs:all>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:all>
</xs:complexType>
</xs:element>
Choice Indicator

71

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The <choice> indicator specifies that either one child element or another can occur:
<xs:element name="person">
<xs:complexType>
<xs:choice>
<xs:element name="employee" type="employee"/>
<xs:element name="member" type="member"/>
</xs:choice>
</xs:complexType>
</xs:element>
Sequence Indicator

The <sequence> indicator specifies that the child elements must appear in a specific order:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

Occurrence Indicators

Occurrence indicators are used to define how often an element can occur.
maxOccurs Indicator

The <maxOccurs> indicator specifies the maximum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" maxOccurs="10"/>
</xs:sequence>
</xs:complexType>
</xs:element>
minOccurs Indicator

The <minOccurs> indicator specifies the minimum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string"
maxOccurs="10" minOccurs="0"/>
</xs:sequence>
</xs:complexType>

72

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

</xs:element>

The example above indicates that the "child_name" element can occur a minimum of zero
times and a maximum of ten times in the "person" element.
Example-2

An XML file called "Myfamily.xml":


<?xml version="1.0" encoding="ISO-8859-1"?>

<persons xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="family.xsd">

<person>
<full_name>Hege Refsnes</full_name>
<child_name>Cecilie</child_name>
</person>

<person>
<full_name>Tove Refsnes</full_name>
<child_name>Hege</child_name>
<child_name>Stale</child_name>
<child_name>Jim</child_name>
<child_name>Borge</child_name>
</person>

<person>
<full_name>Stale Refsnes</full_name>
</person>

</persons>

The XML file above contains a root element named "persons". Inside this root element we
have defined three "person" elements. Each "person" element must contain a "full_name"
element and it can contain up to five "child_name" elements.

Here is the schema file "family.xsd":


<?xml version="1.0" encoding="ISO-8859-1"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">

<xs:element name="persons">
<xs:complexType>
<xs:sequence>
<xs:element name="person" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>

73

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<xs:element name="full_name" type="xs:string"/>


<xs:element name="child_name" type="xs:string"
minOccurs="0" maxOccurs="5"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>
Group Indicators

Group indicators are used to define related sets of elements.


Element Groups

Element groups are defined with the group declaration, like this:
<xs:group name="groupname">
...
</xs:group>

The following example defines a group named "persongroup", that defines a group of
elements that must occur in an exact sequence:
<xs:group name="persongroup">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="birthday" type="xs:date"/>
</xs:sequence>
</xs:group>

After you have defined a group, you can reference it in another definition, like this:
<xs:group name="persongroup">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="birthday" type="xs:date"/>
</xs:sequence>
</xs:group>

<xs:element name="person" type="personinfo"/>

<xs:complexType name="personinfo">
<xs:sequence>
<xs:group ref="persongroup"/>
<xs:element name="country" type="xs:string"/>

74

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

</xs:sequence>
</xs:complexType>
Attribute Groups

Attribute groups are defined with the attributeGroup declaration, like this:
<xs:attributeGroup name="groupname">
...
</xs:attributeGroup>

The following example defines an attribute group named "personattrgroup":


<xs:attributeGroup name="personattrgroup">
<xs:attribute name="firstname" type="xs:string"/>
<xs:attribute name="lastname" type="xs:string"/>
<xs:attribute name="birthday" type="xs:date"/>
</xs:attributeGroup>

After you have defined an attribute group, you can reference it in another definition, like this:
<xs:attributeGroup name="personattrgroup">
<xs:attribute name="firstname" type="xs:string"/>
<xs:attribute name="lastname" type="xs:string"/>
<xs:attribute name="birthday" type="xs:date"/>
</xs:attributeGroup>

<xs:element name="person">
<xs:complexType>
<xs:attributeGroup ref="personattrgroup"/>
</xs:complexType>
</xs:element>
XSD the <any> Element

The <any> element enables us to extend the XML document with elements not specified
by the schema!

The <any> Element

The <any> element enables us to extend the XML document with elements not specified by
the schema.

The following example is a fragment from an XML schema called "family.xsd". It shows a
declaration for the "person" element. By using the <any> element we can extend (after
<lastname>) the content of "person" with any element:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>

75

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<xs:any minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>

Now we want to extend the "person" element with a "children" element. In this case we can
do so, even if the author of the schema above never declared any "children" element.

Look at this schema file, called "children.xsd":


<?xml version="1.0" encoding="ISO-8859-1"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">

<xs:element name="children">
<xs:complexType>
<xs:sequence>
<xs:element name="childname" type="xs:string"
maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>

XSD The <anyAttribute> Element


The <anyAttribute> element enables us to extend the XML document with attributes
not specified by the schema!

The <anyAttribute> Element

The <anyAttribute> element enables us to extend the XML document with attributes not
specified by the schema.

The following example is a fragment from an XML schema called "family.xsd". It shows a
declaration for the "person" element. By using the <anyAttribute> element we can add any
number of attributes to the "person" element:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
<xs:anyAttribute/>

76

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

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

Now we want to extend the "person" element with a "gender" attribute. In this case we can
do so, even if the author of the schema above never declared any "gender" attribute.

Look at this schema file, called "attribute.xsd":


<?xml version="1.0" encoding="ISO-8859-1"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">

<xs:attribute name="gender">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="male|female"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>

</xs:schema>

XSD String Data Types

String data types are used for values that contains character strings.
String Data Type

The string data type can contain characters, line feeds, carriage returns, and tab characters.

The following is an example of a string declaration in a schema:


<xs:element name="customer" type="xs:string"/>

NormalizedString Data Type

The normalizedString data type is derived from the String data type.

The normalizedString data type also contains characters, but the XML processor will remove
line feeds, carriage returns, and tab characters.

The following is an example of a normalizedString declaration in a schema:


<xs:element name="customer" type="xs:normalizedString"/>
Token Data Type

77

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The token data type is also derived from the String data type.

The token data type also contains characters, but the XML processor will remove line feeds,
carriage returns, tabs, leading and trailing spaces, and multiple spaces.

The following is an example of a token declaration in a schema:


<xs:element name="customer" type="xs:token"/>

String Data Types

Note that all of the data types below derive from the String data type (except for string
itself)!
Name Description
ENTITIES
ENTITY
ID A string that represents the ID attribute in XML (only used with
schema attributes)
IDREF A string that represents the IDREF attribute in XML (only used with
schema attributes)
IDREFS
language A string that contains a valid language id
Name A string that contains a valid XML name
NCName
NMTOKEN A string that represents the NMTOKEN attribute in XML (only used
with schema attributes)
NMTOKENS
normalizedStrin A string that does not contain line feeds, carriage returns, or tabs
g
QName
string A string
token A string that does not contain line feeds, carriage returns, tabs, leading
or trailing spaces, or multiple spaces

Restrictions on String Data Types

Restrictions that can be used with String data types:

• enumeration
• length
• maxLength
• minLength
• pattern (NMTOKENS, IDREFS, and ENTITIES cannot use this constraint)
• whiteSpace
XSD Date and Time Data Types

78

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Date and time data types are used for values that contain date and time.

Date Data Type

The date data type is used to specify a date.

The date is specified in the following form "YYYY-MM-DD" where:

• YYYY indicates the year


• MM indicates the month
• DD indicates the day

Note: All components are required!

The following is an example of a date declaration in a schema:


<xs:element name="start" type="xs:date"/>

An element in our document might look like this:


<start>2002-09-24</start>
Time Zones

To specify a time zone, you can either enter a date in UTC time by adding a "Z" behind the
date - like this:
<start>2002-09-24Z</start>

or we can specify an offset from the UTC time by adding a positive or negative time behind
the date - like this:
<start>2002-09-24-06:00</start>

or

<start>2002-09-24+06:00</start>

Time Data Type

The time data type is used to specify a time.

The time is specified in the following form "hh:mm:ss" where:

• hh indicates the hour


• mm indicates the minute
• ss indicates the second

The following is an example of a time declaration in a schema:

79

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<xs:element name="start" type="xs:time"/>

An element in our document might look like this:


<start>09:00:00</start>
Time Zones

To specify a time zone, we can either enter a time in UTC time by adding a "Z" behind the
time - like this:
<start>09:30:10Z</start>

or wecan specify an offset from the UTC time by adding a positive or negative time behind
the time - like this:
<start>09:30:10-06:00</start>

or

<start>09:30:10+06:00</start>

DateTime Data Type

The dateTime data type is used to specify a date and a time.

The dateTime is specified in the following form "YYYY-MM-DDThh:mm:ss" where:

• YYYY indicates the year


• MM indicates the month
• DD indicates the day
• T indicates the start of the required time section
• hh indicates the hour
• mm indicates the minute
• ss indicates the second

Note: All components are required!

The following is an example of a dateTime declaration in a schema:


<xs:element name="startdate" type="xs:dateTime"/>

An element in our document might look like this:


<startdate>2002-05-30T09:00:00</startdate>
Time Zones

To specify a time zone, we can either enter a dateTime in UTC time by adding a "Z" behind
the time - like this:
<startdate>2002-05-30T09:30:10Z</startdate>

80

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

or we can specify an offset from the UTC time by adding a positive or negative time behind
the time - like this:
<startdate>2002-05-30T09:30:10-06:00</startdate>

or

<startdate>2002-05-30T09:30:10+06:00</startdate>
Duration Data Type

The duration data type is used to specify a time interval.

The time interval is specified in the following form "PnYnMnDTnHnMnS" where:

• P indicates the period (required)


• nY indicates the number of years
• nM indicates the number of months
• nD indicates the number of days
• T indicates the start of a time section (required if you are going to specify hours, minutes,
or seconds)
• nH indicates the number of hours
• nM indicates the number of minutes
• nS indicates the number of seconds

The following is an example of a duration declaration in a schema:


<xs:element name="period" type="xs:duration"/>

An element in our document might look like this:


<period>P5Y</period>

The example above indicates a period of five years.


Negative Duration

To specify a negative duration, enter a minus sign before the P:


<period>-P10D</period>

The example above indicates a period of minus 10 days.


Date and Time Data Types
Name Description
date Defines a date value
dateTime Defines a date and time value
duration Defines a time interval
gDay Defines a part of a date - the day (DD)
gMonth Defines a part of a date - the month (MM)
gMonthDay Defines a part of a date - the month and day (MM-DD)
gYear Defines a part of a date - the year (YYYY)

81

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

gYearMonth Defines a part of a date - the year and month (YYYY-MM)


time Defines a time value
Restrictions on Date Data Types

Restrictions that can be used with Date data types:

• enumeration
• maxExclusive
• maxInclusive
• minExclusive
• minInclusive
• pattern
• whiteSpace
XSD Numeric Data Types

Decimal Data Type

The decimal data type is used to specify a numeric value.

The following is an example of a decimal declaration in a schema:


<xs:element name="prize" type="xs:decimal"/>

An element in our document might look like this:


<prize>999.50</prize>

Note: The maximum number of decimal digits you can specify is 18.
Integer Data Type

The integer data type is used to specify a numeric value without a fractional component.

The following is an example of an integer declaration in a schema:


<xs:element name="prize" type="xs:integer"/>

An element in our document might look like this:


<prize>999</prize>

Numeric Data Types

Note that all of the data types below derive from the Decimal data type (except for decimal
itself)!
Name Description
byte A signed 8-bit integer
decimal A decimal value
int A signed 32-bit integer
integer An integer value

82

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

long A signed 64-bit integer


negativeInteger An integer containing only negative values (..,-2,-1)
nonNegativeInte An integer containing only non-negative values (0,1,2,..)
ger
nonPositiveInte An integer containing only non-positive values (..,-2,-1,0)
ger
positiveInteger An integer containing only positive values (1,2,..)
short A signed 16-bit integer
unsignedLong An unsigned 64-bit integer
unsignedInt An unsigned 32-bit integer
unsignedShort An unsigned 16-bit integer
unsignedByte An unsigned 8-bit integer

Restrictions on Numeric Data Types

Restrictions that can be used with Numeric data types:

• enumeration
• fractionDigits
• maxExclusive
• maxInclusive
• minExclusive
• minInclusive
• pattern
• totalDigits
• whiteSpace
XSD Miscellaneous Data Types

Other miscellaneous data types are boolean, base64Binary, hexBinary, float, double,
anyURI, QName, and NOTATION.

Boolean Data Type

The boolean data type is used to specify a true or false value.

The following is an example of a boolean declaration in a schema:


<xs:attribute name="disabled" type="xs:boolean"/>

An element in our document might look like this:


<prize disabled="true">999</prize>

Note: Legal values for boolean are true, false, 1 (which indicates true), and 0 (which
indicates false).
Binary Data Types

83

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Binary data types are used to express binary-formatted data.

We have two binary data types:

• base64Binary (Base64-encoded binary data)


• hexBinary (hexadecimal-encoded binary data)

The following is an example of a hexBinary declaration in a schema:


<xs:element name="blobsrc" type="xs:hexBinary"/>

AnyURI Data Type

The anyURI data type is used to specify a URI.

The following is an example of an anyURI declaration in a schema:


<xs:attribute name="src" type="xs:anyURI"/>

An element in our document might look like this:


<pic src="http://www.w3schools.com/images/smiley.gif" />

Restrictions on Miscellaneous Data Types

Restrictions that can be used with the other data types:

• enumeration (a Boolean data type cannot use this constraint)


• length (a Boolean data type cannot use this constraint)
• maxLength (a Boolean data type cannot use this constraint)
• minLength (a Boolean data type cannot use this constraint)
• pattern
• whitespace

XML DOM Introduction

The XML DOM defines a standard for accessing and manipulating XML.
What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents like XML and HTML:

"The W3C Document Object Model (DOM) is a platform and language-neutral


interface that allows programs and scripts to dynamically access and update the content,
structure, and style of a document."

The DOM is separated into 3 different parts / levels:

84

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• Core DOM - standard model for any structured document


• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents

The DOM defines the objects and properties of all document elements, and
the methods (interface) to access them.
What is the HTML DOM?

The HTML DOM defines the objects and properties of all HTML elements, and
the methods(interface) to access them.
What is the XML DOM?

The XML DOM is:

• A standard object model for XML


• A standard programming interface for XML
• Platform- and language-independent
• A W3C standard

The XML DOM defines the objects and properties of all XML elements, and
the methods (interface) to access them. The XML DOM is a standard for how to get,
change, add, or delete XML elements.

XML DOM Nodes

In the DOM, everything in an XML document is a node.

According to the DOM, everything in an XML document is a node.

The DOM says:

•The entire document is a document node


•Every XML element is an element node
•The text in the XML elements are text nodes
•Every attribute is an attribute node
•Comments are comment nodes
DOM Example

Look at the following XML file (books.xml):


<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>

85

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

The root node in the XML above is named <bookstore>. All other nodes in the document
are contained within <bookstore>.

The root node <bookstore> holds four <book> nodes.

The first <book> node holds four nodes: <title>, <author>, <year>, and <price>, which
contains one text node each, "Everyday Italian", "Giada De Laurentiis", "2005", and "30.00".

The XML DOM Node Tree


The XML DOM views an XML document as a tree-structure. The tree structure is
called a node-tree. All the nodes in the tree have a relationship to each other.

All nodes can be accessed through the tree. Their contents can be modified or deleted,
and new elements can be created.

The node tree shows the set of nodes, and the connections between them. The tree starts
at the root node and branches out to the text nodes at the lowest level of the tree:

86

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The image above represents the XML file books.xml.

Node Parents, Children, and Siblings

The nodes in the node tree have a hierarchical relationship to each other.

The terms parent, child, and sibling are used to describe the relationships. Parent nodes
have children. Children on the same level are called siblings (brothers or sisters).

• In a node tree, the top node is called the root


• Every node, except the root, has exactly one parent node
• A node can have any number of children
• A leaf is a node with no children
• Siblings are nodes with the same parent

The following image illustrates a part of the node tree and the relationship between the
nodes:

87

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Because the XML data is structured in a tree form, it can be traversed without knowing
the exact structure of the tree and without knowing the type of data contained within.
First Child - Last Child

Look at the following XML fragment:


<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>

In the XML above, the <title> element is the first child of the <book> element, and the
<price> element is the last child of the <book> element.

Furthermore, the <book> element is the parent node of the <title>, <author>, <year>, and
<price> elements.
XML DOM Parser

Most browsers have a build-in XML parser to read and manipulate XML.
The parser converts XML into a JavaScript accessible object (the XML DOM).
XML Parser

88

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The XML DOM contains methods (functions) to traverse XML trees, access, insert, and
delete nodes.

However, before an XML document can be accessed and manipulated, it must be loaded
into an XML DOM object.

An XML parser reads XML, and converts it into an XML DOM object that can be
accessed with JavaScript.

Most browsers have a build-in XML parser.


Load an XML Document

The following JavaScript fragment loads an XML document ("books.xml"):


if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // IE 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","books.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML;

Code explained:

• Create an XMLHTTP object


• Open the XMLHTTP object
• Send an XML HTTP request to the server
• Set the response as an XML DOM object

Load an XML String

The following code loads and parses an XML string:

if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");

89

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

xmlDoc.async="false";
xmlDoc.loadXML(text);
}

XML DOM Load Functions

The code for loading XML documents can be stored in a function.

To make the code from the previous page simpler to maintain (and check for older
browsers), it should be written as a function:
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}

The function above can be stored in the <head> section of an HTML page, and called
from a script in the page.

An External JavaScript for loadXMLDoc()

To make the code above even easier to maintain, and to make sure the same code is used
in all pages, we store the function in an external file.

The file is called "loadxmldoc.js", and will be loaded in the head section of an HTML
page. Then, the loadXMLDoc() function can be called from a script in the page.

The following example uses the loadXMLDoc() function to load books.xml:


<html>
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script>
</head>
<body>

<script type="text/javascript">

90

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

xmlDoc=loadXMLDoc("books.xml");

code goes here.....

</script>

</body>
</html>

The loadXMLString() Function

To make the code from the previous page simpler to maintain (and check for older
browsers), it should be written as a function:
function loadXMLString(txt)
{
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(txt);
}
return xmlDoc;
}

The function above can be stored in the <head> section of an HTML page, and called
from a script in the page.
An External JavaScript for loadXMLString()

We have stored the loadXMLString() function in a file called "loadxmlstring.js".


<html>
<head>
<script type="text/javascript" src="loadxmlstring.js"></script>
</head>
<body>
<script type="text/javascript">
text="<bookstore>"
text=text+"<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";

91

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

text=text+"<year>2005</year>";
text=text+"</book>";
text=text+"</bookstore>";

xmlDoc=loadXMLString(text);

code goes here.....

</script>
</body>
</html>

XML DOM - Properties and Methods

Properties and methods define the programming interface to the XML DOM.

Programming Interface

The DOM models XML as a set of node objects. The nodes can be accessed with
JavaScript or other programming languages. In this tutorial we use JavaScript.

The programming interface to the DOM is defined by a set standard properties and
methods.

Properties are often referred to as something that is (i.e. nodename is "book").

Methods are often referred to as something that is done (i.e. delete "book").

XML DOM Properties

These are some typical DOM properties:

• x.nodeName - the name of x


• x.nodeValue - the value of x
• x.parentNode - the parent node of x
• x.childNodes - the child nodes of x
• x.attributes - the attributes nodes of x

Note: In the list above, x is a node object.

XML DOM Methods

• x.getElementsByTagName(name) - get all elements with a specified tag name


• x.appendChild(node) - insert a child node to x
• x.removeChild(node) - remove a child node from x

92

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

XML DOM - Accessing Nodes

With the DOM, you can access every node in an XML document.

Accessing Nodes

We can access a node in three ways:

1. By using the getElementsByTagName() method

2. By looping through (traversing) the nodes tree.

3. By navigating the node tree, using the node relationships.

The getElementsByTagName() Method

getElementsByTagName() returns all elements with a specified tag name.


Syntax
node.getElementsByTagName("tagname");
Example

The following example returns all <title> elements under the x element:
x.getElementsByTagName("title");

Note that the example above only returns <title> elements under the x node. To return all
<title> elements in the XML document use:
xmlDoc.getElementsByTagName("title");

where xmlDoc is the document itself (document node).

DOM Node List

The getElementsByTagName() method returns a node list. A node list is an array of


nodes.

The following code loads "books.xml" into xmlDoc using loadXMLDoc() and stores a
list of <title> nodes (a node list) in the variable x:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title");

The <title> elements in x can be accessed by index number. To access the third <title>
you can write::
y=x[2];

93

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

DOM Node List Length

The length property defines the length of a node list (the number of nodes).

we can loop through a node list by using the length property:


xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title");

for (i=0;i<x.length;i++)
{
document.write(x[i].childNodes[0].nodeValue);
document.write("<br />");
}

Example explained:

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get all <title> element nodes
3. For each title element, output the value of its text node

Node Types

The documentElement property of the XML document is the root node.

The nodeName property of a node is the name of the node.

The nodeType property of a node is the type of the node.

Traversing Nodes

The following code loops through the child nodes, that are also element nodes, of the root
node:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.documentElement.childNodes;

for (i=0;i<x.length;i++)
{
if (x[i].nodeType==1)
{//Process only element nodes (type 1)
document.write(x[i].nodeName);
document.write("<br />");

94

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

}
}

Example explained:

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get the child nodes of the root element
3. For each child node, check the node type of the node. If the node type is "1" it is an
element node
4. Output the name of the node if it is an element node

Navigating Node Relationships

The following code navigates the node tree using the node relationships:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book")[0].childNodes;
y=xmlDoc.getElementsByTagName("book")[0].firstChild;

for (i=0;i<x.length;i++)
{
if (y.nodeType==1)
{//Process only element nodes (type 1)
document.write(y.nodeName + "<br />");
}
y=y.nextSibling;
}

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get the child nodes of the first book element
3. Set the "y" variable to be the first child node of the first book element
4. For each child node (starting with the first child node "y"):
5. Check the node type. If the node type is "1" it is an element node
6. Output the name of the node if it is an element node
7. Set the "y" variable to be the next sibling node, and run through the loop again
XML DOM Node Information

Node Properties

In the XML DOM, each node is an object.

95

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Objects have methods and properties, that can be accessed and manipulated by
JavaScript.

Three important node properties are:

• nodeName
• nodeValue
• nodeType

The nodeName Property

The nodeName property specifies the name of a node.

• nodeName is read-only
• nodeName of an element node is the same as the tag name
• nodeName of an attribute node is the attribute name
• nodeName of a text node is always #text
• nodeName of the document node is always #document

The nodeValue Property

The nodeValue property specifies the value of a node.

• nodeValue for element nodes is undefined


• nodeValue for text nodes is the text itself
• nodeValue for attribute nodes is the attribute value

Get the Value of an Element

The following code retrieves the text node value of the first <title> element:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
txt=x.nodeValue;

Result: txt = "Everyday Italian"

Example explained:

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get text node of the first <title> element node
3. Set the txt variable to be the value of the text node
Change the Value of an Element

96

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The following code changes the text node value of the first <title> element:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";

Example explained:

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get text node of the first <title> element node
3. Change the value of the text node to "Easy Cooking"

The nodeType Property

The nodeType property specifies the type of node.

nodeType is read only.

The most important node types are:


Node type NodeTy
pe
Element 1
Attribute 2
Text 3
Comment 8
Document 9

XML DOM Node List

A list of nodes is returned by the getElementsByTagName() method and the


childNodes property.
DOM Node List

When using properties or methods like childNodes or getElementsByTagName(), a node


list object is returned.

A node list object represents a list of nodes, in the same order as in the XML.

Nodes in the node list are accessed with index numbers starting from 0.

The following image represents a node list of the <title> elements in "books.xml":

97

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The following code fragment loads "books.xml" into xmlDoc using loadXMLDoc() and
returns a node list of title elements in "books.xml":
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title");

After the execution of the statement above, x is a node list object.

The following code fragment returns the text from the first <title> element in the node list
(x) :
txt=x[0].childNodes[0].nodeValue;

After the execution of the statement above, txt = "Everyday Italian".

Node List Length

A node list object keeps itself up-to-date. If an element is deleted or added, the list is
automatically updated.

The length property of a node list is the number of nodes in the list.

98

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The following code fragment loads "books.xml" into xmlDoc using loadXMLDoc() and
returns the number of <title> elements in "books.xml":
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName('title').length;

After the execution of the statement above, x = 4.

The length of the node list can be used to loop through all the elements in the list.

The following code fragment uses the length property to loop through the list of <title>
elements:
xmlDoc=loadXMLDoc("books.xml");

//the x variable will hold a node list


x=xmlDoc.getElementsByTagName('title');

for (i=0;i<x.length;i++)
{
document.write(x[i].childNodes[0].nodeValue);
document.write("<br />");
}

Output:
Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Set the x variable to hold a node list of all title elements
3. Output the value from the text node of all <title> elements

DOM Attribute List (Named Node Map)

The attributes property of an element node returns a list of attribute nodes.

This is called a named node map, and is similar to a node list, except for some differences
in methods and properties.

A attribute list keeps itself up-to-date. If an attribute is deleted or added, the list is
automatically updated.

The following code fragment loads "books.xml" into xmlDoc using loadXMLDoc() and
returns a list of attribute nodes from the first <book> element in "books.xml":
xmlDoc=loadXMLDoc("books.xml");

99

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

x=xmlDoc.getElementsByTagName('book')[0].attributes;

After the execution of the code above, x.length = is the number of attributes and
x.getNamedItem() can be used to return an attribute node.

The following code fragment displays the value of the "category" attribute, and the
number of attributes, of a book:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book")[0].attributes;

document.write(x.getNamedItem("category").nodeValue);
document.write("<br />" + x.length);

Output:
cooking
1

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Set the x variable to hold a list of all attributes of the first <book> element
3. Output the value from the "category" attribute
4. Output the length of the attribute list
XML DOM Traverse Node Tree

Traversing means looping through or traveling across the node tree.

Traversing the Node Tree

Often we want to loop an XML document, for example: when you want to extract the
value of each element.

This is called "Traversing the node tree"

The example below loops through all child nodes of <book>, and displays their names
and values:
<html>
<head>
<script type="text/javascript" src="loadxmlstring.js"></script>
</head>
<body>
<script type="text/javascript">
text="<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";

100

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

text=text+"<year>2005</year>";
text=text+"</book>";

xmlDoc=loadXMLString(text);

// documentElement always represents the root node


x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{
document.write(x[i].nodeName);
document.write(": ");
document.write(x[i].childNodes[0].nodeValue);
document.write("<br />");
}
</script>
</body>
</html>

Output:
title: Everyday Italian
author: Giada De Laurentiis
year: 2005

1. loadXMLString() loads the XML string into xmlDoc


2. Get the child nodes of the root element
3. For each child node, output the node name and the node value of the text node

XML DOM - Navigating Nodes

Nodes can be navigated using node relationships.

Accessing nodes in the node tree via the relationship between nodes, is often called
"navigating nodes".

In the XML DOM, node relationships are defined as properties to the nodes:

• parentNode
• childNodes
• firstChild
• lastChild
• nextSibling
• previousSibling

101

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The following image illustrates a part of the node tree and the relationship between nodes
inbooks.xml:

DOM - Parent Node

All nodes has exactly one parent node. The following code navigates to the parent node
of <book>:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book")[0];
document.write(x.parentNode.nodeName);

Example explained:

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get the first <book> element
3. Output the node name of the parent node of "x"

Avoid Empty Text Nodes

Firefox, and some other browsers, will treat empty white-spaces or new lines as text
nodes, Internet Explorer will not.

102

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

This causes a problem when using the properties: firstChild, lastChild, nextSibling,
previousSibling.

To avoid navigating to empty text nodes (spaces and new-line characters between
element nodes), we use a function that checks the node type:
function get_nextSibling(n)
{
y=n.nextSibling;
while (y.nodeType!=1)
{
y=y.nextSibling;
}
return y;
}

The function above allows you to use get_nextSibling(node) instead of the


propertynode.nextSibling.

Code explained:

Element nodes are type 1. If the sibling node is not an element node, it moves to the next
nodes until an element node is found. This way, the result will be the same in both Internet
Explorer and Firefox.

Get the First Child Element

The following code displays the first element node of the first <book>:
Example
<html>
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script>
<script type="text/javascript">
//check if the first node is an element node
function get_firstChild(n)
{
y=n.firstChild;
while (y.nodeType!=1)
{
y=y.nextSibling;
}
return y;
}
</script>
</head>

103

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<body>
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");

x=get_firstChild(xmlDoc.getElementsByTagName("book")[0]);
document.write(x.nodeName);
</script>
</body>
</html>

Output:
title

XML DOM Get Node Values

The nodeValue property is used to get the text value of a node.


The getAttribute() method returns the value of an attribute.

Get the Value of an Element

In the DOM, everything is a node. Element nodes does not have a text value.

The text of an element node is stored in a child node. This node is called a text node.

The way to get the text of an element, is to get the value of the child node (text node).

Get an Element Value

The getElementsByTagName() method returns a node list containing all elements with
the specified tag name in the same order as they appear in the source document.

The following code loads "books.xml" into xmlDoc using loadXMLDoc() and retrieves
the first <title> element:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0];

The childNodes property returns a list of child nodes. The <title> element has only one
child node. It is a text node.

The following code retrieves the text node of the <title> element:
x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];

The nodeValue property returns the text value of the text node:

104

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];
txt=y.nodeValue;

Result: txt = "Everyday Italian"

Get the Value of an Attribute

In the DOM, attributes are nodes. Unlike element nodes, attribute nodes have text values.

The way to get the value of an attribute, is to get its text value.

This can be done using the getAttribute() method or using the nodeValue property of the
attribute node.

Get an Attribute Value - getAttribute()

The getAttribute() method returns an attribute value.

The following code retrieves the text value of the "lang" attribute of the first <title>
element:
xmlDoc=loadXMLDoc("books.xml");

txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");

Result: txt = "en"

Example explained:

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Set the txt variable to be the value of the "lang" attribute of the first title element node

Loop through all <book> elements and get their "category" attributes: Try it yourself

Get an Attribute Value - getAttributeNode()

The getAttributeNode() method returns an attribute node.

The following code retrieves the text value of the "lang" attribute of the first <title>
element:
xmlDoc=loadXMLDoc("books.xml");

105

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

x=xmlDoc.getElementsByTagName("title")[0].getAttributeNode("lang");
txt=x.nodeValue;

Result: txt = "en"

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get the "lang" attribute node of the first <title> element node
3. Set the txt variable to be the value of the attribute

Loop through all <book> elements and get their "category" attributes: Try it yourself
XML DOM Change Node Values

The nodeValue property is used to change a node value.


The setAttribute() method is used to change an attribute value.

Change the Value of an Element

In the DOM, everything is a node. Element nodes do not have a text value.

The text of an element node is stored in a child node. This node is called a text node.

The way to change the text of an element, is to change the value of the child node (text
node).

Change the Value of a Text Node

The nodeValue property can be used to change the value of a text node.

The following code changes the text node value of the first <title> element:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get the text node of the first <title> element
3. Change the node value of the text node to "Easy Cooking"

Change the Value of an Attribute

In the DOM, attributes are nodes. Unlike element nodes, attribute nodes have text values.

106

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The way to change the value of an attribute, is to change its text value.

This can be done using the setAttribute() method or using the nodeValue property of the
attribute node.

Change an Attribute Using setAttribute()

The setAttribute() method changes the value of an existing attribute, or creates a new
attribute.

The following code changes the category attribute of the <book> element:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("category","food");

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get the first <book> element
3. Change the "category" attribute value to "food"

Change an Attribute Using nodeValue

The nodeValue property can be used to change the value of a attribute node:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book")[0]
y=x.getAttributeNode("category");
y.nodeValue="food";

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get the "category" attribute of the first <book> element
3. Change the attribute node value to "food"
XML DOM Remove Nodes

The removeChild() method removes a specified node.


The removeAttribute() method removes a specified attribute.
Remove an Element Node

The removeChild() method removes a specified node.

When a node is removed, all its child nodes are also removed.

107

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The following code fragment will remove the first <book> element from the loaded xml:
xmlDoc=loadXMLDoc("books.xml");

y=xmlDoc.getElementsByTagName("book")[0];

xmlDoc.documentElement.removeChild(y);

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Set the variable y to be the element node to remove
3. Remove the element node by using the removeChild() method from the parent node

Remove Myself - Remove the Current Node

The removeChild() method is the only way to remove a specified node.

When you have navigated to the node you want to remove, it is possible to remove that
node using the parentNode property and the removeChild() method:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book")[0];

x.parentNode.removeChild(x);

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Set the variable y to be the element node to remove
3. Remove the element node by using the parentNode property and the removeChild()
method

Remove a Text Node

The removeChild() method can also be used to remove a text node:


xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0];

y=x.childNodes[0];
x.removeChild(y);

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Set the variable x to be the first title element node

108

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

3. Set the variable y to be the text node to remove


4. Remove the element node by using the removeChild() method from the parent node
Clear a Text Node

The nodeValue property can be used to change or clear the value of a text node:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="";

Example explained:

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Set the variable x to be the text node of the first title element
3. Use the nodeValue property to clear the text from the text node

Remove an Attribute Node by Name

The removeAttribute(name) method is used to remove an attribute node by its name.

Example: removeAttribute('category')

The following code fragment removes the "category" attribute in the first <book>
element:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book");
x[0].removeAttribute("category");

Example explained:

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Use getElementsByTagName() to get book nodes
3. Remove the "category" attribute form the first book element node

Remove Attribute Nodes by Object

The removeAttributeNode(node) method is used to remove an attribute node, using the


node object as parameter.

Example: removeAttributeNode(x)

The following code fragment removes all the attributes of all <book> elements:
xmlDoc=loadXMLDoc("books.xml");

109

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

x=xmlDoc.getElementsByTagName("book");

for (i=0;i<x.length;i++)
{
while (x[i].attributes.length>0)
{
attnode=x[i].attributes[0];
old_att=x[i].removeAttributeNode(attnode);
}
}

Example explained:

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Use getElementsByTagName() to get all book nodes
3. For each book element check if there are any attributes
4. While there are attributes in a book element, remove the attribute
XML DOM Replace Nodes

The replaceChild() method is used to replace a node.

The following code fragment replaces the first <book> element:


xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.documentElement;

//create a book element, title element and a text node


newNode=xmlDoc.createElement("book");
newTitle=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("A Notebook");

//add the text node to the title node,


newTitle.appendChild(newText);
//add the title node to the book node
newNode.appendChild(newTitle);

y=xmlDoc.getElementsByTagName("book")[0]
//replace the first book node with the new node
x.replaceChild(newNode,y);

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Create a new element node <book>

110

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

3. Create a new element node <title>


4. Create a new text node with the text "A Notebook"
5. Append the new text node to the new element node <title>
6. Append the new element node <title> to the new element node <book>
7. Replace the first <book> element node with the new <book> element node

Replace Data In a Text Node

The replaceData() method is used to replace data in a text node.

The replaceData() method has three parameters:

• offset - Where to begin replacing characters. Offset value starts at zero


• length - How many characters to replace
• string - The string to insert
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];

x.replaceData(0,8,"Easy");

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get the text node of the first <title> element node
3. Use the replaceDat method to replace the eight first characters from the text node
with "Easy"

Use the nodeValue Property Instead

It is easier to replace the data in a text node using the nodeValue property.

The following code fragment will replace the text node value in the first <title> element
with "Easy Italian":
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];

x.nodeValue="Easy Italian";

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Get the text node of the first <title> element node

111

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

3. Use the nodeValue property to change the text of the text node
XML DOM Create Nodes

The createElement() method creates a new element node:


xmlDoc=loadXMLDoc("books.xml");

newel=xmlDoc.createElement("edition");

x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Create a new element node <edition>
3. Append the element node to the first <book> element

Create a New Attribute Node

The createAttribute() is used to create a new attribute node:


xmlDoc=loadXMLDoc("books.xml");

newatt=xmlDoc.createAttribute("edition");
newatt.nodeValue="first";

x=xmlDoc.getElementsByTagName("title");
x[0].setAttributeNode(newatt);

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Create a new attribute node "edition"
3. Set the value of the attribute node to "first"
4. Add the new attribute node to the first <title> element

Create an Attribute Using setAttribute()

Since the setAttribute() method creates a new attribute if the attribute does not exist, it
can be used to create a new attribute.
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("edition","first");

112

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Set (create) the attribute "edition" with the value "first" for the first <book> element

Create a Text Node

The createTextNode() method creates a new text node:


xmlDoc=loadXMLDoc("books.xml");

newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("first");
newel.appendChild(newtext);

x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Create a new element node <edition>
3. Create a new text node with the text "first"
4. Append the new text node to the element node
5. Append the new element node to the first <book> element
Create a Comment Node

The createComment() method creates a new comment node.


xmlDoc=loadXMLDoc("books.xml");

newComment=xmlDoc.createComment("Revised March 2008");

x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newComment);

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Create a new comment node
3. Append the new comment node to the first <book> element
XML DOM Add Nodes

Add a Node - appendChild()

The appendChild() method adds a child node to an existing node.

The new node is added (appended) after any existing child nodes.

113

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The following code fragment creates an element (<edition>), and adds it after the
last child of the first <book> element:
xmlDoc=loadXMLDoc("books.xml");

newel=xmlDoc.createElement("edition");

x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Create a new node <edition>
3. Append the node to the first <book> element

Insert a Node - insertBefore()

The insertBefore() method is used to insert a node before a specified child node.

This method is useful when the position of the added node is important:
xmlDoc=loadXMLDoc("books.xml");

newNode=xmlDoc.createElement("book");

x=xmlDoc.documentElement;
y=xmlDoc.getElementsByTagName("book")[3];

x.insertBefore(newNode,y);

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Create a new element node <book>
3. Insert the new node in front of the last <book> element node

If the second parameter of insertBefore() is null, the new node will be added after the last
existing child node.

x.insertBefore(newNode,null) and x.appendChild(newNode) will both append a new


child node to x.

Add a New Attribute

There is no method called addAtribute().

The setAttribute() method creates a new attribute if the attribute does not exist:
xmlDoc=loadXMLDoc("books.xml");

114

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("edition","first");

1. Load "books.xml" into xmlDoc using loadXMLDoc()


2. Set (create) the attribute "edition" with the value "first" for the first <book> element

Add Text to a Text Node - insertData()

The insertData() method inserts data into an existing text node.

The insertData() method has two parameters:

• offset - Where to begin inserting characters (starts at zero)


• string - The string to insert

The following code fragment will add "Easy" to the text node of the first <title>
element of the loaded XML:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];

x.insertData(0,"Easy ");

XML DOM Clone Nodes

The cloneNode() method creates a copy of a specified node.

The cloneNode() method has a parameter (true or false). This parameter indicates if the
cloned node should include all attributes and child nodes of the original node.

The following code fragment copies the first <book> node and appends it to the root node
of the document:
xmlDoc=loadXMLDoc("books.xml");

oldNode=xmlDoc.getElementsByTagName('book')[0];
newNode=oldNode.cloneNode(true);
xmlDoc.documentElement.appendChild(newNode);

//Output all titles


y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)

115

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

{
document.write(y[i].childNodes[0].nodeValue);
document.write("<br />");
}

Output:
Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML
Everyday Italian

:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Get the node to copy
3. Copy the node into "newNode" using the cloneNode method
4. Append the new node to the the root node of the XML document
5. Output all titles for all books in the document

XML DOM Node Types

The following table lists the different W3C node types, and which node types they may
have as children:
Node type Description Children
Document Represents the entire document Element (max. one),
(the root-node of the DOM tree) ProcessingInstruction,
Comment, DocumentType
DocumentFragment Represents a "lightweight" Element,
Document object, which can hold a ProcessingInstruction,
portion of a document Comment, Text,
CDATASection,
EntityReference
DocumentType Provides an interface to the None
entities defined for the document
ProcessingInstruction Represents a processing None
instruction
EntityReference Represents an entity reference Element,
ProcessingInstruction,
Comment, Text,
CDATASection,
EntityReference
Element Represents an element Element, Text,
Comment,
ProcessingInstruction,
CDATASection,

116

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

EntityReference
Attr Represents an attribute Text, EntityReference
Text Represents textual content in an None
element or attribute
CDATASection Represents a CDATA section in None
a document (text that will NOT be
parsed by a parser)
Comment Represents a comment None
Entity Represents an entity Element,
ProcessingInstruction,
Comment, Text,
CDATASection,
EntityReference
Notation Represents a notation declared in None
the DTD
Node Types - Return Values

The following table lists what the nodeName and the nodeValue properties will return for
each node type:
Node type nodeName returns nodeValue returns
Document #document null
DocumentFragment #document fragment null
DocumentType doctype name null
EntityReference entity reference name null
Element element name null
Attr attribute name attribute value
ProcessingInstruction target content of node
Comment #comment comment text
Text #text content of node
CDATASection #cdata-section content of node
Entity entity name null
Notation notation name null

NodeTypes - Named Constants

NodeType Named Constant


1 ELEMENT_NODE
2 ATTRIBUTE_NODE
3 TEXT_NODE
4 CDATA_SECTION_NODE
5 ENTITY_REFERENCE_NODE
6 ENTITY_NODE
7 PROCESSING_INSTRUCTION_NODE
8 COMMENT_NODE

117

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

9 DOCUMENT_NODE
10 DOCUMENT_TYPE_NODE
11 DOCUMENT_FRAGMENT_NODE
12 NOTATION_NODE
XML DOM - The Node Object
Node Object Properties

Property Description
baseURI Returns the absolute base URI of a node
childNodes Returns a NodeList of child nodes for a node
firstChild Returns the first child of a node
lastChild Returns the last child of a node
localName Returns the local part of the name of a node
namespaceURI Returns the namespace URI of a node
nextSibling Returns the node immediately following a node
nodeName Returns the name of a node, depending on its type
nodeType Returns the type of a node
nodeValue Sets or returns the value of a node, depending on
its type
ownerDocument Returns the root element (document object) for a
node
parentNode Returns the parent node of a node
prefix Sets or returns the namespace prefix of a node
previousSibling Returns the node immediately before a node
textContent Sets or returns the textual content of a node and
its descendants
text Returns the text of a node and its descendants. IE-
only property
xml Returns the XML of a node and its descendants.
IE-only property

Node Object Methods

Method Description
appendChild() Adds a new child node to the end of the list of
children of a node
cloneNode() Clones a node
compareDocumentPosition() Compares the document position of two nodes
getFeature(feature,version) Returns a DOM object which implements the
specialized APIs of the specified feature and version
getUserData(key) Returns the object associated to a key on a this
node. The object must first have been set to this node

118

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

by calling setUserData with the same key


hasAttributes() Returns true if a node has any attributes,
otherwise it returns false
hasChildNodes() Returns true if a node has any child nodes,
otherwise it returns false
insertBefore() Inserts a new child node before an existing child
node
isDefaultNamespace(URI) Returns whether the specified namespaceURI is
the default
isEqualNode() Checks if two nodes are equal
isSameNode() Checks if two nodes are the same node
isSupported(feature,version) Returns whether a specified feature is supported
on a node
lookupNamespaceURI() Returns the namespace URI matching a specified
prefix
lookupPrefix() Returns the prefix matching a specified
namespace URI
normalize() Puts all text nodes underneath a node (including
attributes) into a "normal" form where only structure
(e.g., elements, comments, processing instructions,
CDATA sections, and entity references) separates
Text nodes, i.e., there are neither adjacent Text
nodes nor empty Text nodes
removeChild() Removes a child node
replaceChild() Replaces a child node
setUserData(key,data,handler) Associates an object to a key on a node
XML DOM - The NodeList Object
NodeList Object Properties

Property Description
length Returns the number of nodes in a node list

NodeList Object Methods

Method Description
item() Returns the node at the specified index in a node list

XSLT - XSL Transformations


• XSLT is a language for transforming XML documents into XHTML documents or to
other XML documents.
• XPath is a language for navigating in XML documents.
What is XSLT?
• XSLT stands for XSL Transformations

119

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• XSLT is the most important part of XSL


• XSLT transforms an XML document into another XML document
• XSLT uses XPath to navigate in XML documents
XSLT is a W3C Recommendation

XSLT = XSL Transformations


• XSLT is the most important part of XSL.
• XSLT is used to transform an XML document into another XML document, or
another type of document that is recognized by a browser, like HTML and XHTML.
Normally XSLT does this by transforming each XML element into an (X)HTML
element.
• With XSLT we can add/remove elements and attributes to or from the output file. We
can also rearrange and sort elements, perform tests and make decisions about which
elements to hide and display, and a lot more.
• A common way to describe the transformation process is to say that XSLT
transforms an XML source-tree into an XML result-tree.

Create XML file called Cdcatlog.xml


This XML file does not appear to have any style information associated with it. The
document tree is shown below.
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<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>
<title>Greatest Hits</title>
<artist>Dolly Parton</artist>
<country>USA</country>
<company>RCA</company>
<price>9.90</price>
<year>1982</year>
</cd>
</catalog>

120

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Then you create an XSL Style Sheet ("cdcatalog.xsl") with a transformation template:
<?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>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Link the XSL Style Sheet to the XML Document
Add the XSL style sheet reference to your XML document ("cdcatalog.xml"):
My CD Collection
Title Artist
Empire Burlesque Bob Dylan

Hide your heart Bonnie Tyler

Greatest Hits Dolly Parton


1. The <xsl:template> Element
• The <xsl:template> element is used to build templates.
• The match attribute is used to associate a template with an XML element. The
match attribute can also be used to define a template for the entire XML
document. The value of the match attribute is an XPath expression (i.e. match="/"
defines the whole document).
2. The <xsl:value-of> Element
• The <xsl:value-of> element can be used to extract the value of an XML element and
add it to the output stream of the transformation:

121

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

3. The <xsl:for-each> Element


• The XSL <xsl:for-each> element can be used to select every XML element of a
specified node-se
• Filtering the Output
We can also filter the output from the XML file by adding a criterion to the select
attribute in the <xsl:for-each> element.
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">
Legal filter operators are:
= (equal)
!= (not equal)
&lt; less than
&gt; greater than
4. The <xsl:sort> element is used to sort the output.
5. The <xsl:if> element is used to put a conditional test against the content of the XML
file.
6. The <xsl:choose> element is used in conjunction with <xsl:when> and
<xsl:otherwise> to express multiple conditional tests.
7. The <xsl:apply-templates> Element
• The <xsl:apply-templates> element applies a template to the current element or to
the current element's child nodes.
• If we add a select attribute to the <xsl:apply-templates> element it will process
only the child element that matches the value of the attribute. We can use the
select attribute to specify the order in which the child nodes are processed

Here is the source code needed to transform the XML file to XHTML on the client:
<html>
<head>
<script>
function loadXMLDoc(filename)
{
if (window.ActiveXObject)
{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else
{
xhttp = new XMLHttpRequest();
}
xhttp.open("GET", filename, false);
try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
xhttp.send("");
return xhttp.responseXML;
}

function displayResult()
{

122

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

xml = loadXMLDoc("cdcatalog.xml");
xsl = loadXMLDoc("cdcatalog.xsl");
// code for IE
if (window.ActiveXObject || xhttp.responseType == "msxml-document")
{
ex = xml.transformNode(xsl);
document.getElementById("example").innerHTML = ex;
}
// code for Chrome, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
document.getElementById("example").appendChild(resultDocument);
}
}
</script>
</head>
<body onload="displayResult()">
<div id="example" />
</body>
</html>
• The loadXMLDoc() function does the following:
• Create an XMLHttpRequest object
• Use the open() and send() methods of the XMLHttpRequest object to send a request to a
server
• Get the response data as XML data
• The displayResult() function is used to display the XML file styled by the XSL file:
• Load XML and XSL files
• Test what kind of browser the user has
• If Internet Explorer:
o Use the transformNode() method to apply the XSL style sheet to the xml
document
o Set the body of the current document (id="example") to contain the styled xml
document
• If other browsers:
o Create a new XSLTProcessor object and import the XSL file to it
o Use the transformToFragment() method to apply the XSL style sheet to the xml
document
o Set the body of the current document (id="example") to contain the styled xml
document

123

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

XSLT Elements
The links in the "Element" column point to attributes and more useful
information about each specific element.
Element Description
apply-imports Applies a template rule from an imported style sheet
apply-templates Applies a template rule to the current element or to the current
element's child nodes
attribute Adds an attribute
attribute-set Defines a named set of attributes
call-template Calls a named template
choose Used in conjunction with <when> and <otherwise> to express
multiple conditional tests
comment Creates a comment node in the result tree
copy Creates a copy of the current node (without child nodes and
attributes)
copy-of Creates a copy of the current node (with child nodes and attributes)
decimal-format Defines the characters and symbols to be used when converting
numbers into strings, with the format-number() function
element Creates an element node in the output document
fallback Specifies an alternate code to run if the processor does not support
an XSLT element
for-each Loops through each node in a specified node set
if Contains a template that will be applied only if a specified
condition is true
import Imports the contents of one style sheet into another. Note: An
imported style sheet has lower precedence than the importing style
sheet
include Includes the contents of one style sheet into another. Note: An
included style sheet has the same precedence as the including style
sheet
key Declares a named key that can be used in the style sheet with the
key() function
message Writes a message to the output (used to report errors)
namespace-alias Replaces a namespace in the style sheet to a different namespace in
the output
number Determines the integer position of the current node and formats a
number
otherwise Specifies a default action for the <choose> element
output Defines the format of the output document
param Declares a local or global parameter
preserve-space Defines the elements for which white space should be preserved
processing-instruction Writes a processing instruction to the output
sort Sorts the output
strip-space Defines the elements for which white space should be removed

124

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

stylesheet Defines the root element of a style sheet


template Rules to apply when a specified node is matched
text Writes literal text to the output
transform Defines the root element of a style sheet
value-of Extracts the value of a selected node
variable Declares a local or global variable
when Specifies an action for the <choose> element
with-param Defines the value of a parameter to be passed into a template

XML vocabularies:

The examples of XML vocabularies are as follows:


W3C XML Schema
XSL (Extensible Stylesheet Language)
MathML (Mathematical Markup Language)
SVG (Scalable Vector Graphics)
WML (Wireless Markup Language)
XBRL (Extensible Business Reporting Language)
XUL (Extensible User Interface Language)
PDML (Product Data Markup Language)
MathML

It describe mathematical notations and expressions


Until now, computers use software packages like TeX nad LaTeX for displayinmg
complex mathematical expression
But now we can go with MathML , which is the W3C’s AmayaTM browser / editor ,
which can be downloaded at no charge from
o www.w3.org/Amaya/user/BinDist.html
MathML markup is divided in to two markup languages. They are
Content markup
o This provides tags that embody mathematical concepts
o Allows programmers to write mathematical notation specific to different areas of
mathematics
o Distinguishes between different uses of same symbol
Presentation markup
o It is directed towards formatting and displaying mathematical notation
We embed the MathML content in HTML file by using a math element with the default
Namespace
o http://www.w3.org/1998/Math/MathML
The mrow element is a container element for expressions that contain more than one
element.
The mn element marks up an operator (e.g. +)

<?xml version="1.0"?>

<!-- mathml1.html -->

125

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<!-- Simple MathML -->

<html xmlns="http://www.w3.org/1999/xhtml">

<head><title>Simple MathML Example</title></head>

<body>

<math xmlns = "http://www.w3.org/1998/Math/MathML">

<mrow>
<mn>2</mn>
<mo>+</mo>
<mn>3</mn>
<mo>=</mo>
<mn>5</mn>
</mrow>

</math>
</body>
</html>

Chemical Markup Language (CML)


It is an XML vocabulary for representing molecular and chemical information
CML takes advantage of XML’s portability to enable document authors to use and reuse
molecular information without corrupting important data in the process
Document authors can view and edit CML using the jumbo browser (available at
www.xml-cml.org) or the Jmol browser (available at jmol.sourceforge.net)
The following example shows how to render ammonia molecule rendered by Jmol

<?xml version = "1.0" ?>


<!-- ammonia.xml -->

126

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<!-- Structure of ammonia -->


<molecule id = "ammonia">
<atomArray>
<stringArray builtin = "id" >
Nitrogen Hydrogen1 Hydrogen2 Hydrogen3
</stringArray>
<stringArray builtin = "elementType">
NHHH
</stringArray>
<floatArray builtin = "x3">
-0.7 -1.3 -1.2 -0.7
</floatArray>
<floatArray builtin = "y3">
-0.0 0.2 0.8 -0.9
</floatArray>
<floatArray builtin = "z3">
0.0 -0.9 0.6 0.6
</floatArray>
</atomArray>
</molecule>

Here the example defines the ammonia molecule using element molecule
Attribute id identifies this molecule as ammonia

127

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

A molecule is composed of atoms. The atomArray elements used to specify one or more
atoms that comprise the molecule
The atomarray element is used to specify one or more atoms that comprise the molecule
It uses the stringArray and assign id to attribute built-in to specify the id’s of the atoms
that make up the molecule
Ammonia contains one nitrogen atom and three hydrogen atoms
The allowed values of element-Type include every element –Type include every element on
the periodic table
The use of element floatArray with attribute built-in assigned to the value x3 to specify a list
of floating-point numbers.
Each number defines the x-coordinate of each atom
The first value (-0.7) is the x-coordinate of the first atom (nitrogen), the second value is the
x-coordinate of the second atom
Then we also have define the z-coordinate

RSS
It stands for RDF ( Resource Description frame work )Site summary and is also known as
Rich Site Summary and Really Simple Syndication
It is a Popular and simple XML format designed to share headlines and Web content between
Web sites
We can view various RSS formatted headlines and content at
www.brokenvaporware.com/ht/rss
The below sample shows a RSS 2.0 file
An RSS file , also called RSS feed, consists of a container rss element that denotes the RSS
version and Container channel elements
RSS feeds can then contain descriptive tags and item elements that describe the news or
information
Each item elements has a title element , a description element and a link element
An aggregator is one type of RSS program it keeps tracks of many RSS feeds and brings
together information from the separate feeds
<?xml version = "1.0" ?>
<!-- deitel.rss -->
<!-- RSS feed -->
<rss version = "2.0">
<channel>
<title>Deitel</title>
<link>http://www.deitel.com</link>
<description>CS textbooks</description>
<language>en-us</language>
<item>
<title>Simply VB How To Program</title>
<description>
This book combines the DEITEL signature live-code approach
with a new application-driven methodology, in which readers
build real-world applications that incorporate Visual
Basic .NET programming fundamentals.

128

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

</description>
<link>
http://www.deitel.com/books/downloads.html#vbnetHTP2
</link>
</item>
<item>
<title>Visual C++ </title>
<title>Simply VB How To Program</title>
<description>
This book combines the DEITEL signature live-code approach
with a new application-driven methodology, in which readers
build real-world applications that incorporate Visual
Basic .NET programming fundamentals.
</description>
<link>
http://www.deitel.com/books/downloads.html#vbnetHTP2
</link>
</item>
<item>
<title>Visual C++ </title>
<description>
For experienced programmers. Pictures of pyramids
on the cover.
</description>
<link>
http://www.deitel.com/books/vbnetFEP1
</link>
</item>
</channel>
</rss>

129

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

UNIT V INTRODUCTION TO AJAX and WEB SERVICES


AJAX: Ajax Client Server Architecture-XML Http Request Object-Call Back Methods; Web
Services: Introduction- Java web services Basics – Creating, Publishing ,Testing and Describing
a Web services (WSDL)-Consuming a web service, Database Driven web service from an
application –SOAP.

Ajax - Asynchronous JavaScript


What is Ajax?

Asynchronous JavaScript and XML or Ajax for short is new web development
technique used for the development of most interactive website. Ajax helps in making web
application more interactive by retrieving small amount of data from web server and then
showing it on application without refreshing our page

Usually in all the web applications, the user enters the data into the form and then clicks on the
submit button to submit the request to the server. Server processes the request and returns the
view in new page (by reloading the whole page). This process is inefficient, time consuming,
and a little frustrating for you user if the only the small amount of data exchange is required.
For example in an user registration form, this can be frustrating thing for the user, as whole
page is reloaded only to check the availability of the user name. Ajax will help in making your
application more interactive. With the help of Ajax you can tune your application to check the
availability of the user name without refreshing the whole page.

Understanding the technology behind Ajax

Ajax is not a single technology, but it is a combination of many technologies. These


technologies are supported by modern web browsers. Following are techniques used in the
Ajax applications.

• JavaScript:

JavaScript is used to make a request to the web server. Once the response is returned by
the web server, more JavaScript can be used to update the current page. DHTML and
CSS is used to show the output to the user. JavaScript is used very heavily to provide the
dynamic behavior to the application.

• Asynchronous Call to the Server:


Most of the Ajax application used the XMLHttpRequest object to send the request to the
web server. These calls are Asynchronous and there is no need to wait for the response to
1

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

come back. User can do the normal work without any problem.

• XML:
XML may be used to receive the data returned from the web server. JavaScript can be
used to process the XML data returned from the web server easily.

How Ajax Works? (Client Server Architecture)

When user first visits the page, the Ajax engine is initialized and loaded. From that point of
time user interacts with Ajax engine to interact with the web server. The Ajax engine operates
asynchronously while sending the request to the server and receiving the response from server.
Ajax life cycle within the web browser can be divided into following stages:

• User Visit to the page: User visits the URL by typing URL in browser or clicking a link
from some other page.

• Initialization of Ajax engine:


When the page is initially loaded, the Ajax engine is also initialized. The Ajax engine can
also be set to continuously refresh the page content without refreshing the whole page.

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• Event Processing Loop:


* Browser event may instruct the Ajax engine to send request to server and receive the
response data
* Server response - Ajax engine receives the response from the server. Then it calls the
JavaScript call back functions
* Browser (View) update - JavaScript request call back functions is used to update the
browser. DHTML and css is used to update the browser display.

Benefits of Ajax

Ajax is new very promising technology, which has become extremely popular these days.
Here are the benefits of using Ajax:

• Ajax can be used for creating rich, web-based applications that look and works like a
desktop application

• Ajax is easy to learn. Ajax is based on JavaScript and existing technologies like XML,
CSS, DHTML. etc. So, its very easy to learn Ajax

• Ajax can be used to develop web applications that can update the page data continuously
without refreshing the whole page

The Role of AJAX in enhancing the user experience on the Web

AJAX is not a new technology but a combination of several existing technologies in a new
way. These include HTML, CSS, DOM, XML, XSLT, XMLHttpRequest and Javascript. The
acronym AJAX stands for Asynchronous Javascript and XML. AJAX is based on open
standards supported by many browsers and platforms. AJAX is a new paradigm for building
web application.

AJAX applications eliminate the start-stop-start-stop nature of traditional web pages hence
allow web application to look and behave like the desktop ones, of course to a limited
extent. AJAX allows pages to request small bits of information from the server instead
of entire pages. This incremental updating of pages eliminates the page refresh problem and
slow response that have plagued Web applications since their inception.
AJAX has received tremendous industry recognition and support. The major software giants
and web portals have adopted it. A large number of AJAX toolkits and libraries are available
for free. AJAX does have its limitation but most of them can be overcome by integrating
AJAX with other technologies whenever required.

AJAX is here to change the user experience on desktop as well as on mobile devices.

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Rich Internet Applications

According to Wikipedia Rich Internet Applications (RIA) are web applications that have the
features and functionality of traditional desktop applications. RIA's transfer the processing
necessary for the user interface to the web client but keep the bulk of the data back on the
application server.
Traditional web applications centered all activity around a client-server architecture with all
processing done on the server, and the client only displaying static content. The biggest
drawback with this system is that all interaction must pass through the server, which requires
data to be sent to the server, the server to respond, and the page to be reloaded on the client
with the response. Most traditional web applications have clumsier and difficult to use
interfaces compared to desktop ones. The primary difference between a RIA and traditional
web applications is the amount and quality of interaction between the user and the interface.
An RIA can use a wider range of controls to improve users’ interaction allowing efficient
interactions, better error management, feedback and overall user experience. Another benefit
of RIAs is that data can be cached in the client, allowing a vastly more responsive user
interface and fewer round trips to the server.

Some of the features and benefits delivered by RIA's are listed below
a) Allows feedback, confirmation and errors messages to be displayed on same page/view.

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

b) Wider variety of controls e.g. sliders, date pickers, windows, tabs, spinners etc.

c) No installation, just an AJAX enabled browser required


d) Higher immunity to viruses and piracy.
e) Reduced load on server resources as processing is distributes over server and client
f) Lowered application development and deployment costs
g) Reduction in network traffic due to more intelligent client and selective data request
The most common technologies used for building RIA's are Java applets and web start, Adobe
Flash and Flex, and AJAX. Efforts are being made to make AJAX work with the other
mentioned technologies. Adobe Systems has released libraries to help developers bridge
Adobe Flash and Flex technology with AJAX. Similarly libraries are available to integrate
AJAX with Java,.NET, PHP, Python, Perl, Ruby and other backend technologies.

What can AJAX do?

AJAX is playing a crucial role in making Web 2.0 promises a reality. Some of the features
of web 2.0 are
a) Use of Web as the platform
b) Software delivered as a service instead of packaged software
c) Cost-effective scalability
d) Architecture with user participation
AJAX interfaces are a key component of many Web 2.0 applications. Google, Yahoo,
Microsoft, Amazon and many others have embraced AJAX.

Google services like Maps, Gmail, Suggest, Reader use it. Google Maps, which is considered
as one of the most impressive and popular AJAX based application, allows user to zoom in
and out and scroll the map in four directions very much like a desktop application. User can
drag the map on screen with the mouse pointer and double click to center. All this with no
clicking and waiting for graphics to reload each time you want to view the adjacent parts of a
map. Gmail uses AJAX for spell-check, auto save, new email check and other functions. In
Google suggest suggestions are provided in real time as the user types the search query.
Yahoo's Flickr and instant search use AJAX. In Flickr the text-editing and tagging interface
uses it. Instant search gives user the result as he/she is typing the query. Yahoo frontpage too
has been AJAXified.

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Windows Live is a free AJAX virtual desktop. Some of its features are search, news, maps,
email integration, instant messenger, contact management tool etc. More features can be
included through the use of third party 'Gadgets'.
Meebo is a web based instant messenger client, it supports Yahoo, Gtalk, MSN and AIM
protocols. Writely, Zoho, gOffice, AjaxOffice are AJAX based online word processors; some
are full-fledged office suits. Digg is a technology news website that combines social
bookmarking, blogging, RSS, and non-hierarchical editorial control. Travbuddy lets users
create travel journals and share travel experiences, reviews and photos. This application also
uses Google Maps. Pageflakes, Netvibes and Protopage are free startpages.

Zimbra is an AJAX based collaboration suit. Kiko and Calendarhub are online calendars.
Pixoh is an online photo editing application

The impact of AJAX on user experience

AJAX user interfaces are highly responsive giving users the feeling that changes are
instantaneous. It also introduces multiple segments of interactivity on the same page. User
may submit a form and immediately after concentrate on some text or click on a menu item in
some other segment. Even in case of an error in one segment other segments can stay usable.
AJAX applications usually avoid the need of horizontal and vertical scrollbars, this adds to
user convenience.
Existing AJAX applications can be categorized into two types 1) partially AJAXed - here
AJAX is used to provide certain functionalities e.g. Flickr and 2) fully AJAXed - here
AJAX is necessary for functionalities as well as for user-interface e.g. Meebo, Google Maps,
Windows Live
The way users use fully AJAXed applications is very different from their traditional web
experience. In these applications the concept of web pages breaks down, surfing a site or using
an applications is not just clicking links and loading fresh pages. In some applications the
response may result in changes to small/certain parts of the current view, the URL in the
address bar remains unchanged and the Back, Forward, Reload and Bookmark buttons are
rendered meaningless. The browser is not certain to show the previous state of the application
on hitting Back/Forward buttons. Users need to adapt to this change in browser behavior.
Some of the processes/elements in user experience which have undergone AJAXification
are mentioned below

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

a) Hierarchical tree navigation - users find it irritating to navigate trees in Directories


and Discussion threads, AJAX makes expansion/contraction of tree nodes smooth
without making the user wait for the new page to load
b) Form value check - as the user fills in a online form an AJAX call could be made to the
server to do tasks like checking availability of user name, measure strength of password,
populate drop-down boxes further down based on data already entered. Also auto-completion
and spell-check features can be provided
c) Rapid user-user communication - browser based chat applications and games can be built
without the need to manually refresh the page to get current data/state
d) Data filtering and rearranging - this include applying a filter, sorting by date or some
particular column values, relocate iframes, divs and page elements
e) Server-side pushes - AJAX enables simulation of server-side push technology using polling

Traditional Means of Web Application Development


In the early days the web pages were static, simple HTML web pages, later on it became
dynamic by using CGI script (Perl was mostly used), Microsoft's Active Server Pages (ASP)
were among the few popular languages to develop dynamic pages. But small changes in the
page forced to took a round trip from the browser to server.
In the early days the application forms has to be filled and submitted to the server by pressing
the submit button. After that the whole page was processed by the server and a new page sent
back to browser. This causes many round trip to the server.
Early developers strove to develop a new technology to overcome this situation, at early stage
the efforts were ad hoc in nature and complex too.
After that new technique took place like nested frames, iframe etc. Nested frames have the
problems to reload the entire page to display a single change in the page. This technique
allowed developers to update only selected portion of a page. Hidden iframe are another
technique, in this technique user has to made requests through hidden frames which is inserted
by html and JavaScript. This technique is much similar to AJAX, it has the ability to submit
the form without refreshing the page, again when server sent back data that is accessed
by JavaScript.
Another way is remote scripting which uses <src> tag to access any JavaScript file or coding.
It is cleaner than iframe technique, JavaScript tag generated on the server successfully loaded
on the web page.
Traditional Web sites use synchronous techniques in which users has to wait for the response
of the requests which has been made by the user and on the other hand the server has to keep
waiting when user do his work.

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Ajax Web Architecture


Web applications evolve. From static HTML sites first to AJAX applications more recently,
through multiple dynamic technologies (PHP, ASP, Java, and Ruby on Rails…), Web
application architectures and their dedicated tools regularly experience major advancements and
breakthroughs.

Here is the main principle: the server no longer manages the whole page but only sends raw data
to the client; all the pages generation and user interactions management is done on the client
side, that is to say in the browser.

This diagram illustrates the evolution of Web application architectures:

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Model 1: classic Web application

On the first diagram, the Web application is mainly executed on the server side. It sends directly
to the browser HTML pages, CSS and possibly JavaScript enhancing the behavior. Then, for
each user action requiring new data, the server is queried and returns a whole new HTML page.

Model 2: AJAX Web application

The second diagram introduces the AJAX pattern, for Asynchronous JavaScript and XML,
which appeared in the mid-2000s).
This architecture principle can make the application more responsive by reducing exchanges
between browser and server. When a user action generates a client call to retrieve new data, the
server only returns view fragments. Thus, only a small part of the screen is refreshed, rather than
the entire page. This requires the development of client-side JavaScript in order to manage
partial refreshments, for example by using the jQuery library and its $.Ajax function or others
tools more integrated with server platforms (such as Java Server Faces or Google Web Toolkit
for Java environments).

This architecture brought more reactivity but also more complexity. It has many pitfalls:

• the extensive use of jQuery can make impossible the application maintenance,
without implementing complex technical rules (offered today by MV* frameworks like
Backbone.js and AngularJS)
• despite their aim to ease developments, server-side frameworks like Java Server Faces
turned out to be very heavy and complex, leading to many bugs and performance
issues.

Model 3: client-side MV* Web application

The third diagram shows the new MV* client-side architecture, whose principle disrupts with
the previous ones: now the server sends only raw unformatted data and the client is
responsible for generating the screen out of it.
The term MV* refers to the MVC pattern, for Model View Controller, widely used server-side to
separate data and views management. More and more we use this term MV*, in order to
highlight the little differences from pure MVC implementations. But this is an expert
discussion…

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The important point in this new architecture is the shift of all the UI logic from the server to
the client.
This separation of concerns between server and client is not a new phenomenon. It has been
taken back by native mobile applications, consuming APIs independent from the client. The new
Web application architectures bring this possibility to Web applications.

JavaScript development industrialization

JavaScript development ecosystem, which can be summarized in two main categories:


• Development frameworks: while we had libraries like jQuery before for easing
JavaScript development, developers now have proper frameworks for structuring their
applications. There are two advantages: accelerating development and ensuring a better
maintainability of the code. As of today, the best frameworks are AngularJS, Backbone.js
and Ember.js.
• Industrialization tools: the industrialization of JavaScript development has exploded in
the past two years, heavily inspired by what already existed for other platforms such as
Java. The same way Java developers use Maven, JavaScript developers can now use
Grunt to automate testing and build their application, as well as applying the specific
front-end development workflow

• The industrialization is also driven by the fact that JavaScript is spreading over other
areas than just Web applications, especially server-side with node.js.

Ajax as Web application Development

10

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

AJAX is a web application development technique which encompasses different technologies


which make it more interesting and fun. It has the following technologies :

1. JavaScript
2. XML
3. CSS
4. W3C DOM
5. XMLHttpRequest

Since it embraces so many technologies that's why it is neither easy nor tough. In
AJAX, "A"stands for "Asynchronous" that means sending data from the browser and
response send back from the server are not sequential. When user make requests then the
server can do its own work or it may fulfill other requests. Similarly when server is busy in
responding user may make further requests that means no request or response is synchronous
or depending on each other.
Data Exchange in AJAX

XML: In AJAX, data is exchanged with the help of XML files, there are many alternate
techniques are also available like CSV, JSON etc.
11

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Because of the simplicity of XML, it is becoming the new standard of exchanging data
between server and browser. XML is very easy to reformat, reuse.
DOM: The DOM (Document Object Model) is the object oriented representation of XML &
HTML documents, and provides an API for changing the content, structure, and style. The
DOM represents HTML & XML documents as object hierarchy, which is easy to parse by
XML tools.
CSS: CSS (Cascading Style Sheet) is used in web site for designing purpose, we can use CSS
in almost all aspects of the way the web pages look, size, color, width, length etc. of text box,
input area,..etc. that means every attribute of every user interface. In AJAX it is very useful to
use CSS, you can implement CSS as color changing on validation checking in
a registration form and other.

XMLHttpRequest: Unlike other usual web pages, with AJAX, JavaScript communicates
with server using JavaScript's XMLHttpRequest object. With the help of XMLHttpRequest a
web page can send request and get a response from the server without refreshing the page.
This object is supported by all the leading web browsers.

JavaScript: We can say that JavaScript is the pivot point of AJAX . IT performs the following
role in AJAX:

1. Handling XMLHttpRequest made HTTP requests


2. Using DOM, XSLT or any other method, parsing the response come from the server.
3. Presenting the response from server to user interface

Advantages and Disadvantages of AJAX

Advantages:

1. XMLHttpRequest - It is used for making requests to the non-Ajax pages. It supports all
kind of HTTP request type.

2. IFrame - It can make requests using both POST and GET methods. It supports every
modern browsers. It supports asynchronous file uploads
3. Cookies - In spite of implementation difference among browsers it supports large
number of browsers
4. The interface is much responsive, instead of the whole page, a section of the page is
transferred at a time.
5. Waiting time is reduced
6. Traffic to and from the server is reduced.
12

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Disadvantages:

1. XMLHttpRequest -In the older version of IE (5 & 6) ActiveX to be enabled, this feature
is available in new browsers and latest version of few.
2. IFrame - Requests have to be asynchronous. The design of the Server pages must be
compatible with IFrame requests There is an implementation difference among
different browsers. Unnecessary history records can be left on the history record of the
browser. Request size is increased due to the fact that data is URL-encoded.
3. Cookies - It prohibits no synchronous requests, it does not cope with large
requests/results The server pages requires to be designed to work with cookie requests.

Ajax Web Framework

According to the features of the Ajax framework, it is of following types:

1. Direct Ajax frameworks


2. Indirect Ajax frameworks
3. Ajax component frameworks
4. Server-driven Ajax frameworks

Direct Ajax frameworks


To these frameworks developer requires the knowledge of HTML, CSS, JavaScript and Ajax.
In this kind of framework developer authors the HTML and the api directly interacts with the
HTML elements. These frameworks provide the API for DOM manipulation, event handling
and animation support. This framework can't be used for complex application such as Ajax
Web based email client.
Indirect Ajax frameworks
These Ajax frameworks relies on a compiler technology that actually converts the high level
language into Ajax, HTML and JavaScript. In such framework high level language is used
which generates the JavaScript from the high level language. To use Indirect Ajax
frameworks, developer must know CSS, HTML. There is no requirement of knowing the Ajax
and Javascript as framework generates Ajax and JavaScript code.

Ajax component frameworks


The Ajax component frameworks provides lot of premade components such as grid, tabbed
panel, tree, combo box, date picker, HTML editors etc. We can use these components while
developing the UI for your web applications. These framework allows the developer to use
these components by just adding few lines of JavaScript or XML tags.
The Ajax component framework allows the developer to rapidly
develop web applications. These frameworks provides:

13

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

1. Customizable API and event handling functions.


2. Skinning facilities for great looking website
3. Programmatic control of the components
4. The extensibility support, which make the framework very useful. You can create own
components by extending the existing one.

Server-driven Ajax frameworks

The Server-driven Ajax frameworks relies on the server side components for the Ajax
functionality. In such type of framework programmer's develops and manage the server side
components and the server generates necessary HTML and JavaScript for Ajax support. The
server-side framework renders the component(s) and handle the server client request response
data handling.

XMLHttpRequest Object:
As the use of XML and web services is increasing day by day, it is good to connect an HTML
page with XML, with the help of that we can get interim updates so easily without reloading
the page. It is possible due to the XMLHttpRequest object, which is responsible for retrieving
and submitting the XML data directly from the client side. It relies on Document Object
Model (DOM) to convert the retrieved XML data into HTML.
Microsoft first implemented the XMLHttpRequest object in IE 5 for Windows as an ActiveX
object. Afterward Mozilla and Apple's Safari also implemented in their own style.

XMLHttpRequest object facilitates the web developer a lot because with the help of this object
you can update the page with new data without reloading the page, communicate with server
in the background, request and receive data from the web server.

Creating an XMLHttpRequest object.

We can create an instance of the XMLHttpRequest in most of the modern popular browsers,
and in the old versions of the browsers we need to create an object of ActiveXObject.
var xmlobj=new XMLHttpRequest ();
var activeobj=new ActiveXObject("Microsoft.XMLHTTP");

How to use an XMLHttpRequest Object and Handle the server response:

We need to create an XMLHttpRequest, after that we will use few important functions like:

1. onreadystatechange property: After submitting the request to the server, we need to


store the response from the server. onreadystatechange property stores the response from
the function which process the server.
14

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

2. readystate property: readystate property holds the state of the server response, every
time readystate property change , onreadystatechange function executes. Possible values
and their meaning are given below:

State The Request is:


0 Not initialized
1 Has been set up
2 Has been sent
3 In process
4 Is complete

3. responseText property: The data sent back from the server is stored and retrieved later
with the help of responseText property.

AJAX Example
In the following example we will see how to display server IP address dynamically with the
help of AJAX, HTML, & PHP.
SimpleAjax.html
<html>
<body>
<script type="text/javascript" >
function ajaxfunction()
{
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.timeform.time.value=xmlhttp.responseText;
15

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

}
}
xmlhttp.open("GET","SimpleAjax.php",true);
xmlhttp.send(null);
}
</script>
<form name="timeform" >
Name:<input type="text" name="Name" onkeyup="ajaxfunction()"; />
<br/>
Time:<input type="text" name="time"/>
</form>
</body>
</html>

SimpleAjax.php
<?php
echo ($SERVER_ADDR);
?>
SimpleAjax.html
<html>
<body>
<script type="text/javascript" >
function ajaxfunction()
{
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{

16

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

document.timeform.time.value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","SimpleAjax.php",true);
xmlhttp.send(null);
}
</script>
<form name="timeform" >
Name:<input type="text" name="Name" onkeyup="ajaxfunction()"; />
<br/>
Time:<input type="text" name="time"/>
</form>
</body>
</html>

Note: In this way we can get different dynamic values of server and other like time, date
etc.

Ajax First Example - Print Date and Time


we will create a simple Ajax Applicationfor displaying the current date and time. Date and
time information are retrieved asynchronously from the server side php script. Our HTML
page calls serverside php script to retrieve the today's date. Once the time data is retrieved
from the server, it usesjavascript and css to display the time on the HTML page.

The server side script is developed in PHP that displays the current time of the server. You
modify thephp to display your own message. This program can also be used to do some
business processing.

These days Ajax is being used extensively for the development of interactive websites. There
are many frameworks available these days to develop Ajax applications. But you should start
learning the Ajax from scratch. This is the first example in Ajax that will give you quick start
in the Ajax technologies.

Let's get started with the Ajax technology and develop our fist Ajax Datetime example.

Here is the code of HTML File:

<html>
17

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<head>

<title>Ajax Example</title>

<script language="Javascript">

function postRequest(strURL) {

var xmlHttp;

if (window.XMLHttpRequest) { // Mozilla, Safari, ...

var xmlHttp = new XMLHttpRequest();

} else if (window.ActiveXObject) { // IE

var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

xmlHttp.open('POST', strURL, true);

xmlHttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');

xmlHttp.onreadystatechange = function() {

if (xmlHttp.readyState == 4) {

updatepage(xmlHttp.responseText);

xmlHttp.send(strURL);

function updatepage(str){

document.getElementById("result").innerHTML =
"<font color='red' size='5'>" + str + "</font>";;
18

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

function showCurrentTime(){

var rnd = Math.random();

var url="time.php?id="+rnd;

postRequest(url);

</script>

</head>

<body>

<h1 align="center"><font color="#000080">Ajax Example</font></h1>

<p><font color="#000080">&nbsp;This very simple Ajax Example retrieves the

current date and time from server and shows on the form. To view the current

date and time click on the following button.</font></p>

<form name="f1">

<p align="center"><font color="#000080">&nbsp;<input value=" Show Time"


type="button" onclick='JavaScript:showCurrentTime()'
name="showdate"></font></p>

<div id="result" align="center"></div>

</form>

<div id=result></div>

</body>

</html>

19

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

When use clicks on the "Show Time" button, the showCurrentTime() is called. The
the function showCurrentTime() calls the time.php using Ajax and then updates the
time values retrieved from server.
Here is the code of PHP (time.php) file:
<?
print date("l M dS, Y,
H:i:s");
?>

The above PHP code prints current date and time.

Ajax Multiplication Program


Ajax is a web development technique where we can send the request to server
without refreshing the page. Here we will multiply two values and display the
result on the page. This program calls the method 'callmultiply()' for the
multiplying the values entered by user. The multiplication operation is performed
20

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

in the 'multiply.php' page at serverside. The 'callmultiply()' sends the numbers as url
string by calling the 'postRequest()' method. The 'postRequest()' method generates
Ajax call to serverside script 'multiply.php'. And finally 'updatepage()' method
updates the multiplication result on the html page.

Example of Ajax multiplication program:


<html>
<head>
<title>Ajax Multiply Example</title>
<script language="Javascript">
function postRequest(strURL){
var xmlHttp;
if(window.XMLHttpRequest){ // For Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject){ // For Internet Explorer
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('POST', strURL, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4){
updatepage(xmlHttp.responseText);
}
}
xmlHttp.send(strURL);
}

function updatepage(str){
document.getElementById('result').value = str;
}

function callMultiply(){
var a = parseInt(document.f1.a.value);

21

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

var b = parseInt(document.f1.b.value);
var url = "multiply.php?a=" + a + "&b=" + b + "";
postRequest(url);
}
</script>
</head>

<body>
<h1 align="center"><font color="#000080">Ajax Example</font></h1>
<form name="f1">
<input name="a" id="a" value="">
<input name="b" id="b" value="">
<input name="result" type="text" id="result">
<input type="button" value="Multiply" onClick="callMultiply()"
name="showmultiply">
</form>
</body>
</html>

Here is the code of the "multiply.php" page:


<?
$a=$_GET["a"];
$b=$_GET["b"];
$mul=$a*$b;
echo $mul;
?>

22

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Ajax Login Program


In this program we will learn how to validate the user and show alert message if
user name or password are not correct. These days almost all the e-comm
applications requires authentication before accessing the secured part of the web
site. In this program we will show how you can send ajax request to authenticate the
user.

When a user input username and password and press Login button,
'call_login()' function is called. This method sends ajax request to server
(login.php) to validate the user. We have hardcoded the authonication mechanism
e.g. if you enter login name admin and password admin then the program will show
you success message. Otherwise it will show login failed message. You can change
the authentication logic in the page and easily authenticate use from database.
23

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Example of Ajax login Program :


<html>
<head>
<script language="javascript">
function postRequest(strURL){
var xmlHttp;
if(window.XMLHttpRequest){ // For Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject){ // For Internet Explorer
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('POST', strURL, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4){
updatepage(xmlHttp.responseText);
}
}
xmlHttp.send(strURL);
}

function updatepage(str){
if(str=="yes"){
alert("Welcome User");
}else{
alert("Invalid Login! Please try again!");
}
}

function call_login(){
var username = window.document.f1.username.value;
var password = window.document.f1.password.value;
var url = "login.php?username=" + username + "&password=" +password ;
postRequest(url);
}
</script>
</head>
24

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<body>
<Center>

<form name="f1" onsubmit="return call_login();">


<table border="0" bgcolor="#CCCCFF" cellspacing="1" cellpadding="3" width="287">
<tr>
<td align="left" colspan="2" width="275"><b><font size="5"
color="#000080">Login</font></b></td>
</tr>
<tr>
<td align="right" width="81"><b><font color="#000080">User
Name:</font></b></td>
<td width="184"><input type="text" name="username" id="user" size="20" value="" /></td>
</tr>
<tr>
<td align="right" width="81"><b><font color="#000080">Password:</font></b></td>
<td width="184"><input type="password" name="password" size="20" value="" /></td>
</tr>
<tr>
<td colspan="2" align="center" width="275"><input type="button" name="a1" value="Login"
onclick="call_login()"></td>
</tr>
</table>
</form>

</center>
</body>
</html>

Here is the code for login.php page:


<?
$username=$_GET["username"];
$password=$_GET["password"];
if($username=="admin" && $password=="admin"){
echo "yes";

25

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

}else{
echo "No";
}
?>

Output

Ajax Registration Program


In this Ajax Registration program we will learn how to validate the user registration
through ajax call and then display the alert massage if no values are provided in the
username and password fields.
When a user input user Id and password and press Register button , method
'call_Register()' will make ajax call. If the value returned from the server is "yes"
the alert box will show 'Welcome for Register' otherwise it will show ' the Invalid
Id/password please enter the Id/password!'.
Example of Ajax Registration program:
<html>

26

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<head>

<title>Ajax Registratiion program</title>

<script language="javascript">

function postRequest(strURL){

var xmlHttp;

if(window.XMLHttpRequest){ // For Mozilla, Safari, ...

var xmlHttp = new XMLHttpRequest();

else if(window.ActiveXObject){ // For Internet Explorer

var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

xmlHttp.open('POST', strURL, true);

xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xmlHttp.onreadystatechange = function(){

if (xmlHttp.readyState == 4){

updatepage(xmlHttp.responseText);

xmlHttp.send(strURL);

}
function updatepage(str){

if(str == "no"){

27

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

alert("Invalid Id/password! Please fill Currect Id/password")

}
else{

alert("welcome for register !");

function call_register(){

var login_id =document.reg.uid.value;

var password=document.reg.passwd.value;

var url = "Register.php?loginid="+login_id+"&password="+password+"";

postRequest(url);

</script>

</head>

<body>

<center>

<form name="reg">

<table border="1" width="30%">

<tr>

<td align="center" colspan="2"> <font face="Monotype" size="5">Registration</font></td>

</tr>

<tr>

<td> Login id: </td> <td> <input type="text" name="uid" size="20"></td>


28

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

</tr>

<tr>

<td> Password: </td><td><input type="password" name="passwd" size="20" /></td>

</tr>

<tr>

<td align="center" colspan="2"> <input type="submit" value="Register" onClick="return


call_register()"

style="background-color:#FFE9D2;color:#0000FF; border-color:#99CC33"> </td>

</tr>
</table>

</form>

</body>
</html>
Here this code support the Register.php for Ajax Registration program:
<?
$loginid=$_GET["loginid"];
$password=$_GET["password"];
if( $password == "" || $loginid == "" || ($loginid == "" && $password == "") ){
echo "no";
}
else{
echo "yes";
}
?>

Output

29

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Web services

Web Services can convert your applications into Web-applications.


Web Services are published, found, and used through the Web.

What are web services

• Web service is any piece of software that makes itself available over the internet and
uses a standardized XML messaging system. XML is used to encode all communications
to a web service. For example, a client invokes a web service by sending an XML
message, then waits for a corresponding XML response. Because all communication is in
XML, web services are not tied to any one operating system or programming language--
Java can talk with Perl; Windows applications can talk with Unix applications.
• Web Services are self-contained, modular, distributed, dynamic applications that can be
described, published, located, or invoked over the network to create products, processes,

30

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

and supply chains. These applications can be local, distributed, or Web-based. Web
services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and
XML.
• Web services are XML-based information exchange systems that use the Internet for
direct application-to-application interaction. These systems can include programs,
objects, messages, or documents.
• A web service is a collection of open protocols and standards used for exchanging data
between applications or systems. Software applications written in various programming
languages and running on various platforms can use web services to exchange data over
computer networks like the Internet in a manner similar to inter-process communication
on a single computer. This interoperability (e.g., between Java and Python, or Windows
and Linux applications) is due to the use of open standards

31

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Thus we can summarize web services as follows:

• Web services are application components


• Web services communicate using open protocols
• Web services are self-contained and self-describing
• Web services can be discovered using UDDI
• Web services can be used by other applications
• XML is the basis for Web services

Components of Web Services

The basic Web services platform is XML + HTTP. All the standard Web Services works
using following components

• SOAP (Simple Object Access Protocol)


• UDDI (Universal Description, Discovery and Integration)
• WSDL (Web Services Description Language)
32

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

How does it Work?

We can build a Java-based Web Service on Solaris that is accessible from your Visual
Basic program that runs on Windows. We can also use C# to build new Web Services on
Windows that can be invoked from your Web application that is based on JavaServer Pages
(JSP) and runs on Linux.

An Example

Consider a simple account-management and order -processing system. The accounting


personnel use a client application built with Visual Basic or JSP to create new accounts and enter
new customer orders.

The processing logic for this system is written in Java and resides on a Solaris machine, which
also interacts with a database to store the information.

The steps illustrated above are as follows:

1. The client program bundles the account registration information into a SOAP message.
2. This SOAP message is sent to the Web Service as the body of an HTTP POST request.
3. The Web Service unpacks the SOAP request and converts it into a command that the
application can understand. The application processes the information as required and
responds with a new unique account number for that customer.
4. Next, the Web Service packages up the response into another SOAP message, which it
sends back to the client program in response to its HTTP request.
5. The client program unpacks the SOAP message to obtain the results of the account
registration process. For further details regarding the implementation of Web Services
technology, read about the Cape Clear product set and review the product components.

Benefits of using Web Services

• Exposing the existing function on to network:

A Web service is a unit of managed code that can be remotely invoked using
HTTP, that is, it can be activated using HTTP requests. So, Web Services allows you to
expose the functionality of your existing code over the network. Once it is exposed on the
network, other application can use the functionality of your program.

• Connecting Different Applications i.e. Interoperability:

Web Services allows different applications to talk to each other and share data
and services among themselves. Other applications can also use the services of the web
services. For example VB or .NET application can talk to java web services and vice
33

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

versa. So, Web services are used to make the application platform and technology
independent.

• Standardized Protocol:

Web Services uses standardized industry standard protocol for the communication. All
the four layers (Service Transport, XML Messaging, Service Description and Service
Discovery layers) use the well defined protocol in the Web Services protocol stack. This
standardization of protocol stack gives the business many advantages like wide range of
choices, reduction in the cost due to competition and increase in the quality.
• Low Cost of communication:

Web Services uses SOAP over HTTP protocol for the communication, so you can
use your existing low cost internet for implementing Web Services. This solution is much
less costly compared to proprietary solutions like EDI/B2B. Beside SOAP over HTTP,
Web Services can also be implemented on other reliable transport mechanisms like FTP
etc.

Characteristics of Web services XML-based

Web Services uses XML at data representation and data transportation layers. Using
XML eliminates any networking, operating system, or platform binding. So Web
Services based applications are highly interoperable application at their core level.

• Loosely coupled

A consumer of a web service is not tied to that web service directly. The web
service interface can change over time without compromising the client's ability to
interact with the service. A tightly coupled system implies that the client and server logic
are closely tied to one another, implying that if one interface changes, the other must also
be updated. Adopting a loosely coupled architecture tends to make software systems
more manageable and allows simpler integration between different systems.

• Coarse-grained

Object-oriented technologies such as Java expose their services through


individual methods. An individual method is too fine an operation to provide any useful
capability at a corporate level. Building a Java program from scratch requires the creation
of several fine-grained methods that are then composed into a coarse-grained service that
is consumed by either a client or another service. Businesses and the interfaces that they

34

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

expose should be coarse-grained. Web services technology provides a natural way of


defining coarse-grained services that access the right amount of business logic.

• Ability to be synchronous or asynchronous

Synchronicity refers to the binding of the client to the execution of the service. In
synchronous invocations, the client blocks and waits for the service to complete its
operation before continuing. Asynchronous operations allow a client to invoke a service
and then execute other functions. Asynchronous clients retrieve their result at a later point
in time, while synchronous clients receive their result when the service has completed.
Asynchronous capability is a key factor in enabling loosely coupled systems.

• Supports Remote Procedure Calls (RPCs)

Web services allow clients to invoke procedures, functions, and methods on


remote objects using an XML-based protocol. Remote procedures expose input and
output parameters that a web service must support. Component development through
Enterprise JavaBeans (EJBs) and .NET Components has increasingly become a part of
architectures and enterprise deployments over the past couple of years. Both technologies
are distributed and accessible through a variety of RPC mechanisms. A web service
supports RPC by providing services of its own, equivalent to those of a traditional
component, or by translating incoming invocations into an invocation of an EJB or a
.NET component.

• Supports document exchange


One of the key advantages of XML is its generic way of representing not only data,
but also complex documents. These documents can be simple, such as when representing a
current address, or they can be complex, representing an entire book or RFQ. Web services
support the transparent exchange of documents to facilitate business integration.

Web service Architecture

There are two ways to view the web service architecture.

• The first is to examine the individual roles of each web service actor.
• The second is to examine the emerging web service protocol stack.

1. Web Service Roles

There are three major roles within the web service architecture:

• Service provider:

35

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

This is the provider of the web service. The service provider implements the service and
makes it available on the Internet.

• Service requestor

This is any consumer of the web service. The requestor utilizes an existing web service
by opening a network connection and sending an XML request.

• Service registry

This is a logically centralized directory of services. The registry provides a central place
where developers can publish new services or find existing ones. It therefore serves as a
centralized clearinghouse for companies and their services.

2. Web Service Protocol Stack

A second option for viewing the web service architecture is to examine the emerging web service
protocol stack. The stack is still evolving, but currently has four main layers.

• Service transport

This layer is responsible for transporting messages between applications. Currently, this
layer includes hypertext transfer protocol (HTTP), Simple Mail Transfer Protocol
(SMTP), file transfer protocol (FTP), and newer protocols, such as Blocks Extensible
Exchange Protocol (BEEP).

• XML messaging

This layer is responsible for encoding messages in a common XML format so that
messages can be understood at either end. Currently, this layer includes XML-RPC and
SOAP.

• Service description

This layer is responsible for describing the public interface to a specific web service.
Currently, service description is handled via the Web Service Description Language
(WSDL).

• Service discovery

This layer is responsible for centralizing services into a common registry, and providing
easy publish/find functionality. Currently, service discovery is handled via Universal
Description, Discovery, and Integration (UDDI).

36

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

As web services evolve, additional layers may be added, and additional technologies may

Service Transport

The bottom of the web service protocol stack is service transport. This layer is responsible for
actually transporting XML messages between two computers.

• Hyper Text Transfer Protocol (HTTP)

Currently, HTTP is the most popular option for service transport. HTTP is simple, stable,
and widely deployed. Furthermore, most firewalls allow HTTP traffic. This allows
XMLRPC or SOAP messages to masquerade as HTTP messages. This is good if you
want to easily integrate remote applications, but it does raise a number of security
concerns.

• Blocks Extensible Exchange Protocol (BEPP)

One promising alternative to HTTP is the Blocks Extensible Exchange Protocol


(BEEP).BEEP is a new IETF framework of best practices for building new protocols.
BEEP is layered directly on TCP and includes a number of built-in features, including an
initial handshake protocol, authentication, security, and error handling. Using BEEP, one
can create new protocols for a variety of applications, including instant messaging, file
transfer, content syndication, and network management

SOAP

SOAP is an XML-based protocol for exchanging information between computers.


SOAP is XML. That is, SOAP is an application of the XML specification.

• SOAP is acronym for Simple Object Access Protocol


• SOAP is a communication protocol
• SOAP is designed to communicate via Internet
• SOAP can extend HTTP for XML messaging
• SOAP provides data transport for Web services
• SOAP can exchange complete documents or call a remote procedure
• SOAP can be used for broadcasting a message
• SOAP is platform and language independent
• SOAP is the XML way of defining what information gets sent and how

Although SOAP can be used in a variety of messaging systems and can be delivered via a variety
of transport protocols, the initial focus of SOAP is remote procedure calls transported via HTTP.

37

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

SOAP enables client applications to easily connect to remote services and invoke remote
methods.

Other frameworks, including CORBA, DCOM, and Java RMI, provide similar functionality to
SOAP, but SOAP messages are written entirely in XML and are therefore uniquely platform-and
language-independent.

SOAP Message Structure

A SOAP message is an ordinary XML document containing the following elements.

• Envelope: ( Mandatory )
Defines the start and the end of the message.
• Header: ( Optional )
Contains any optional attributes of the message used in processing the message, either at
an intermediary point or at the ultimate end point.
• Body: ( Mandatory )
Contains the XML data comprising the message being sent.
• Fault: ( Optional )
An optional Fault element that provides information about errors that occurred while
processing the message

A SOAP Message Structure

<?xml version="1.0"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<SOAP-ENV:Header>
...
...
</SOAP-ENV:Header>
<SOAP-ENV:Body>

...
...
<SOAP-ENV:Fault>
...
...
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP_ENV:Envelope>
SOAP Envelope Element
38

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The SOAP envelope indicates the start and the end of the message so that the receiver knows
when an entire message has been received. The SOAP envelope solves the problem of knowing
when you're done receiving a message and are ready to process it. The SOAP envelope is
therefore basic ally a packaging mechanism

SOAP Envelope element can be explained as:

• Every SOAP message has a root Envelope element.


• Envelope element is mandatory part of SOAP Message.
• Every Envelope element must contain exactly one Body element.
• If an Envelope contains a Header element, it must contain no more than one, and it must
appear as the first child of the Envelope, beforethe Body.
• The envelope changes when SOAP versions change.
• The SOAP envelope is specified using the ENV namespace prefix and
theEnvelope element.
• The optional SOAP encoding is also specified using a namespace name and the
optional encodingStyle element, which could also point to an encoding style other than
the SOAP one.
• A v1.1-compliant SOAP processor will generate a fault when receiving a message
containing the v1.2 envelope namespace.
• A v1.2- compliant SOAP processor generates a VersionMismatch fault if it receives a
message that does not include the v1.2 envelope namespace.

<?xml version="1.0"?>

<SOAP-ENV:Envelope

xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"

SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

...

Message information goes here

...

</SOAP-ENV:Envelope>

Following example illustrates the use of a SOAP message within an HTTP POST operation,
which sends the message to the server. It shows the namespaces for the envelope schema
39

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

definition and for the schema definition of the encoding rules. The OrderEntry reference in the
HTTP header is the name of the program to be invoked at the tutorialspoint.com Web site.

POST /OrderEntry HTTP/1.1

Host: www.tutorialspoint.com

Content-Type: application/soap; charset="utf-8"

Content-Length: nnnn

<?xml version="1.0"?>

<SOAP-ENV:Envelope

xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"

SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

...

Message information goes here

...

</SOAP-ENV:Envelope>

SOAP Header Element

The optional Header element offers a flexible framework for specifying additional application-
level requirements. For example, the Header element can be used to specify a digital signature
for password-protected services; likewise, it can be used to specify an account number for pay-
per-use SOAP services.

SOAP Header element can be explained as:

• Header elements are optional part of SOAP messages.


• Header elements can occur multiple times.
• Headers are intended to add new features and functionality
• The SOAP header contains header entries defined in a namespace.
• The header is encoded as the first immediate child element of the SOAP envelope.
• When more than one header is defined, all immediate child elements of the SOAP header
are interpreted as SOAP header blocks.

40

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

SOAP Header element can have following two attributes

• Actor attribute:
The SOAP protocol defines a message path as a list of SOAP service nodes. Each of
these intermediate nodes can perform some processing and then forward the message to
the next node in the chain. By setting the Actor attribute, the client can specify the
recipient of the SOAP header.
• MustUnderstand attribute
Indicates whether a Header element is optional or mandatory. If set to true ie. 1 the
recipient must understand and process the Header attribute according to its defined
semantics, or return a fault.

<?xml version="1.0"?>

<SOAP-ENV:Envelope

xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"

SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<SOAP-ENV:Header>

<t:Transaction

xmlns:t="http://www.tutorialspoint.com/transaction/"

SOAP-ENV:mustUnderstand="true">5</t:Transaction>

</SOAP-ENV:Header>

...

...

</SOAP-ENV:Envelope>

SOAP Body Element

The SOAP body is a mandatory element which contains the application-defined XML data being
exchanged in the SOAP message. The body must be contained within the envelope and must
follow any headers that might be defined for the message. The body is defined as a child element
of the envelope, and the semantics for the body are defined in the associated SOAP schema.

41

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

The body contains mandatory information intended for the ultimate receiver of the message. For
example:

<?xml version="1.0"?>

<SOAP-ENV:Envelope

........

<SOAP-ENV:Body>

<m:GetQuotation xmlns:m="http://www.tp.com/Quotation">

<m:Item>Computers</m:Item>

</m:GetQuotation>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>

The example above requests the quotation of computer sets. Note that the m:GetQuotation and
the Item elements above are application-specific elements. They are not a part of the SOAP
standard.

Here is the response of above query:

<?xml version="1.0"?>

<SOAP-ENV:Envelope

........

<SOAP-ENV:Body>

<m:GetQuotationResponse xmlns:m="http://www.tp.com/Quotation">

<m:Quotation>This is Qutation</m:Quotation>

42

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

</m:GetQuotationResponse>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>

Normally, the application also defines a schema to contain semantics associated with the request
and response elements.

The Quotation service might be implemented using an EJB running in an application server; if
so, the SOAP processor would be responsible for mapping the body information as parameters
into and out of the EJB implementation of theGetQuotationResponse service. The SOAP
processor could also be mapping the body information to a .NET object, a CORBA object, a
COBOL program, and so on.

SOAP Fault Element

When an error occurs during processing, the response to a SOAP message is a SOAP fault
element in the body of the message, and the fault is returned to the sender of the SOAP message.

The SOAP fault mechanism returns specific information about the error, including a predefined
code, a description, the address of the SOAP processor that generated

• A SOAP Message can carry only one fault block


• Fault element is an optional part of SOAP Message
• For the HTTP binding, a successful response is linked to the 200 to 299 range of status
codes;
• SOAP fault is linked to the 500 to 599 range of status codes.

The SOAP Fault element has the following sub elements:

Sub Element

Description

<faultCode>

A text code used to indicate a class of errors. See the next Table for a listing of predefined fault
codes.

<faultString>

43

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

A text message explaning the error

<faultActor>

A text string indicating who caused the fault. This is useful if the SOAP message travels through
several nodes in the SOAP message path, and the client needs to know which node caused the
error. A node that does not act as the ultimate destination must include a faultActor element.

<detail>

An element used to carry application-specific error messages. The detail element can contain
child elements, called detail entries.

SOAP Fault Codes

The faultCode values defined below must be used in the faultcode element when describing
faults

Error

Description

SOAP-ENV:VersionMismatch

Found an invalid namespace for the SOAP Envelope element

SOAP-ENV:MustUnderstand

An immediate child element of the Header element, with the mustUnderstand attribute set to "1",
was not understood

SOAP-ENV:Client

The message was incorrectly formed or contained incorrect information

SOAP-ENV:Server

There was a problem with the server so the message could not proceed

SOAP Fault Example

The following code is a sample Fault. The client has requested a method named
ValidateCreditCard , but the service does not support such a method. This represents a client
request error, and the server returns the following SOAP response:

44

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

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

<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode xsi:type="xsd:string">SOAP-ENV:Client</faultcode>
<faultstring xsi:type="xsd:string">
Failed to locate method (ValidateCreditCard) in class
(examplesCreditCard) at /usr/local/ActivePerl-5.6/lib/
site_perl/5.6.0/SOAP/Lite.pm line 1555.
</faultstring>

</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

SOAP Encoding

• SOAP includes a built-in set of rules for encoding data types.This enables the SOAP
message to indicate specific data types, such as integers, floats, doubles, or arrays.
• SOAP data types are divided into two broad categories: scalar types and compound types.
• Scalar types contain exactly one value, such as a last name, price, or product description.
• Compound types contain multiple values, such as a purchase order or a list of stock
quotes.
• Compound types are further subdivided into arrays and structs.
• The encoding style for a SOAP message is set via the SOAP-ENV:encodingStyle
attribute.
• SOAP arrays have a very specific set of rules, which require that you specify both the
element type and array size. SOAP also supports multidimensional arrays, but not all
SOAP implementations support multidimensional functionality.

SOAP Transport

• OAP is not tied to any one transport protocol.


• SOAP can be transported via SMTP, FTP, IBM's MQSeries, or Microsoft Message
Queuing (MSMQ).
• SOAP specification includes details on HTTP only.
• HTTP remains the most popular SOAP transport protocol.
45

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

SOAP via HTTP

SOAP requests are sent via an HTTP request and SOAP responses are returned within the
content of the HTTP response. While SOAP requests can be sent via an HTTP GET, the
specification includes details on HTTP POST only.

Additionally, both HTTP requests and responses are required to set their content type to text/xml.

The SOAP specification mandates that the client must provide a SOAPAction header, but the
actual value of the SOAPAction header is dependent on the SOAP server implementation.

SOAP Examples
In the example below, a GetQuotation request is sent to a SOAP Server over HTTP. The request
has a QuotationName parameter, and a Quotation will be returned in the response.

The namespace for the function is defined in "http://www.xyz.org/quotation" address.

Here is the SOAP request:

POST /Quotation HTTP/1.0

Host: www.xyz.org

Content-Type: text/xml; charset=utf-8

Content-Length: nnn

<?xml version="1.0"?>

<SOAP-ENV:Envelope

xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"

SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<SOAP-ENV:Body xmlns:m="http://www.xyz.org/quotations">

<m:GetQuotation>

<m:QuotationsName>MiscroSoft</m:QuotationsName>

46

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

</m:GetQuotation>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>

A corresponding SOAP response will look like :

HTTP/1.0 200 OK

Content-Type: text/xml; charset=utf-8

Content-Length: nnn

<?xml version="1.0"?>

<SOAP-ENV:Envelope

xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"

SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<SOAP-ENV:Body xmlns:m="http://www.xyz.org/quotation">

<m:GetQuotationResponse>

<m:Quotation>Here is the quotation</m:Quotation>

</m:GetQuotationResponse>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>

47

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

WSDL (Web Services Description Language )

• WSDL stands for Web Services Description Language


• WSDL is an XML based protocol for information exchange in decentralized and
distributed environments.
• WSDL is the standard format for describing a web service.
• WSDL definition describes how to access a web service and what operations it will
perform.
• WSDL is a language for describing how to interface with XML-based services.
• WSDL is an integral part of UDDI, an XML-based worldwide business registry.
• WSDL is the language that UDDI uses.
• WSDL was developed jointly by Microsoft and IBM.
• WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'

WSDL Usage:

WSDL is often used in combination with SOAP and XML Schema to provide web services over
the Internet. A client program connecting to a web service can read the WSDL to determine what
functions are available on the server. Any special datatypes used are embedded in the WSDL file
in the form of XML Schema. The client can then use SOAP to actually call one of the functions
listed in the WSDL.

History of WSDL

WSDL 1.1 was submitted as a W3C Note by Ariba, IBM and Microsoft for describing services
for the W3C XML Activity on XML Protocols in March 2001.

WSDL 1.1 has not been endorsed by the World Wide Web Consortium (W3C), however it has
just (May 11th, 2005) released a draft for version 2.0, that will be a recommendation (an official
standard), and thus endorsed by the W3C.

WSDL Elements

WSDL breaks down Web services into three specific, identifiable elements that can be combined
or reused once defined.

Three major elements of WSDL that can be defined separately and they are:

• Types
• Operations
48

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• Binding

A WSDL document has various elements, but they are contained within these three main
elements, which can be developed as separate documents and then they can be combined or
reused to form complete WSDL files.

Following are the elements of WSDL document. Within these elements are further subelements,
or parts:

• Definition: element must be the root element of all WSDL documents. It defines the
name of the web service, declares multiple namespaces used throughout the remainder of
the document, and contains all the service elements described here.
• Data types: the data types - in the form of XML schemas or possibly some other
mechanism - to be used in the messages
• Message: an abstract definition of the data, in the form of a message presented either as
an entire document or as arguments to be mapped to a method invocation.
• Operation: the abstract definition of the operation for a message, such as naming a
method, message queue, or business process, that will accept and process the message
• Port type : an abstract set of operations mapped to one or more end points, defining the
collection of operations for a binding; the collection of operations, because it is abstract,
can be mapped to multiple transports through various bindings.
• Binding: the concrete protocol and data formats for the operations and messages defined
for a particular port type.
• Port: a combination of a binding and a network address, providing the target address of
the service communication.
• Service: a collection of related end points encompassing the service definitions in the
file; the services map the binding to the port and include any extensibility definitions.

In addition to these major elements, the WSDL specification also defines the following utility
elements:

• Documentation: element is used to provide human-readable documentation and can be


included inside any other WSDL element.
• Import: element is used to import other WSDL documents or XML Schemas.

The WSDL Document Structure

The main structure of a WSDL document looks like this:

<definitions>
<types>
definition of types........
</types>

49

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<message>
definition of a message....
</message>

<portType>
<operation>
definition of a operation.......
</operation>
</portType>

<binding>
definition of a binding....
</binding>

<service>
definition of a service....
</service>

</definitions>

A WSDL document can also contain other elements, like extension elements and a service
element that makes it possible to group together the definitions of several web services in one
single WSDL document.

WSDL Document Example

Following is the WSDL file that is provided to demonstrate a simple WSDL program.

Assuming the service provides a single publicly available function, called sayHello. This
function expects a single string parameter and returns a single string greeting. For example if you
pass the parameter world then service function sayHello returns the greeting, "Hello, world!".

Content of HelloService.wsdl file

<definitions name="HelloService"
targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">

50

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<message name="SayHelloRequest">
<part name="firstName" type="xsd:string"/>
</message>
<message name="SayHelloResponse">
<part name="greeting" type="xsd:string"/>
</message>

<portType name="Hello_PortType">
<operation name="sayHello">
<input message="tns:SayHelloRequest"/>
<output message="tns:SayHelloResponse"/>
</operation>
</portType>

<binding name="Hello_Binding" type="tns:Hello_PortType">


<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="sayHello">
<soap:operation soapAction="sayHello"/>
<input>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</output>
</operation>
</binding>

<service name="Hello_Service">
<documentation>WSDL File for HelloService</documentation>
<port binding="tns:Hello_Binding" name="Hello_Port">
<soap:address
location="http://www.examples.com/SayHello/">
</port>
</service>
</definitions>

51

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Analysis of the Example

• Definition : HelloService
• Type : Using built-in data types and they are defined in XMLSchema.
• Message :
1. sayHelloRequest : firstName parameter
2. sayHelloresponse: greeting return value
• Port Type: sayHello operation that consists of a request and response service.
• Binding: Direction to use the SOAP HTTP transport protocol.
• Service: Service available at http://www.examples.com/SayHello/.
• Port: Associates the binding with the URI http://www.examples.com/SayHello/ where
the running service can be accessed.

WSDL Definition Element

The <definition> element must be the root element of all WSDL documents. It defines the name
of the web service.

Here is the example piece of code from last session which uses definition element.

<definitions name="HelloService"

targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl"

xmlns="http://schemas.xmlsoap.org/wsdl/"

xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"

xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"

xmlns:xsd="http://www.w3.org/2001/XMLSchema">

................................................

</definitions>

• The definitions element is a container of all the other elements.


• The definitions element specifies that this document is the HelloService.
• The definitions element specifies a targetNamespace attribute. ThetargetNamespace is a
convention of XML Schema that enables the WSDL document to refer to itself. In this
example we have specified atargetNamespace of
http://www.examples.com/wsdl/HelloService.wsdl.

52

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• The definition element specifies a default namespace:


xmlns=http://schemas.xmlsoap.org/wsdl/. All elements without a namespace prefix, such
as message or portType, are therefore assumed to be part of the default WSDL
namespace.
• It also specifies numerous namespaces that will be used throughout the remainder of the
document.

WSDL Types Element

A Web service needs to define its inputs and outputs and how they are mapped into and out of
services. WSDL <types> element take care of defining the data types that are used by the web
service. Types are XML documents, or document parts.

• The types element describes all the data types used between the client and server.
• WSDL is not tied exclusively to a specific typing system
• WSDL uses the W3C XML Schema specification as its default choice to define data
types.
• If the service uses only XML Schema built-in simple types, such as strings and integers,
then types element is not required.
• WSDL allows the types to be defined in separate elements so that the types are reusable
with multiple Web services.

<types>
<schema targetNamespace="http://example.com/stockquote.xsd"
xmlns="http://www.w3.org/2000/10/XMLSchema">
<element name="TradePriceRequest">
<complexType>
<all>
<element name="tickerSymbol" type="string"/>
</all>
</complexType>
</element>
<element name="TradePrice">
<complexType>
<all>
<element name="price" type="float"/>
</all>
</complexType>
</element>
</schema>
</types>

53

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

Data types address the problem of how to identify the data types and format you intend to use
with your Web services. Type information is shared between sender and receiver. The recipients
of messages therefore need access to the information you used to encode your data and must
understand how to decode the data.
WSDL Message Element

• he <message> element describes the data being exchanged between the Web service
providers and consumers.
• Each Web Service has two messages: input and output.
• The input describes the parameters for the Web Service and the output describes the
return data from the Web Service.
• Each message contains zero or more <part> parameters, one for each parameter of the
Web Service's function.
• Each <part> parameter associates with a concrete type defined in the<types> container
element.

<message name="SayHelloRequest">

<part name="firstName" type="xsd:string"/>

</message>

<message name="SayHelloResponse">

<part name="greeting" type="xsd:string"/>

</message>

Here, two message elements are defined. The first represents a request messageSayHelloRequest,
and the second represents a response messageSayHelloResponse.

Each of these messages contains a single part element. For the request, the part specifies the
function parameters; in this case, we specify a single firstName parameter. For the response, the
part specifies the function return values; in this case, we specify a single greeting return value.

WSDL portType Element

The <portType> element combines multiple message elements to form a complete oneway or
round-trip operation.

54

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

For example, a <portType> can combine one request and one response message into a single
request/response operation. This is most commonly used in SOAP services. A portType can
define multiple operations.

Lets take a piece of code from the Example Session:

<portType name="Hello_PortType">
<operation name="sayHello">
<input message="tns:SayHelloRequest"/>
<output message="tns:SayHelloResponse"/>
</operation>
</portType>

• The portType element defines a single operation, called sayHello.


• The operation itself consists of a single input message SayHelloRequest
• The operation itself consists of a single output message SayHelloResponse

Patterns of Operation

WSDL supports four basic patterns of operation:

One-way :

The service receives a message. The operation therefore has a single inputelement. The grammar
for a one-way operation is:

<wsdl:definitions .... > <wsdl:portType ..... > *


<wsdl:operation name="nmtoken">
<wsdl:input name="nmtoken"? message="qname"/>
</wsdl:operation>
</wsdl:portType >
</wsdl:definitions>
Request-response:

The service receives a message and sends a response. The operation therefore has
one input element, followed by one output element. To encapsulate errors, an
optional fault element can also be specified. The grammar for a request-response operation is:

<wsdl:definitions ..... >


<wsdl:portType ..... > *
<wsdl:operation name="nmtoken" parameterOrder="nmtokens">
<wsdl:input name="nmtoken"? message="qname"/>
<wsdl:output name="nmtoken"? message="qname"/>

55

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<wsdl:fault name="nmtoken" message="qname"/>*


</wsdl:operation>
</wsdl:portType >
</wsdl:definitions>
Solicit-response:

The service sends a message and receives a response. The operation therefore has
one output element, followed by one input element. To encapsulate errors, an
optional fault element can also be specified. The grammar for a solicit-response operation is:

<wsdl:definitions ..... >


<wsdl:portType ..... > *
<wsdl:operation name="nmtoken" parameterOrder="nmtokens">
<wsdl:output name="nmtoken"? message="qname"/>
<wsdl:input name="nmtoken"? message="qname"/>
<wsdl:fault name="nmtoken" message="qname"/>*
</wsdl:operation>
</wsdl:portType >
</wsdl:definitions>
Notification :

The service sends a message. The operation therefore has a single outputelement. Following is
the grammer for a notification operation:

<wsdl:definitions ..... >


<wsdl:portType ..... > *
<wsdl:operation name="nmtoken">
<wsdl:output name="nmtoken"? message="qname"/>
</wsdl:operation>
</wsdl:portType >
</wsdl:definitions>

WSDL Binding Element

• The <binding> element provides specific details on how a portType operation will
actually be transmitted over the wire.
• The bindings can be made available via multiple transports, including HTTP GET, HTTP
POST, or SOAP.
• The bindings provide concrete information on what protocol is being used to
transfer portType operations.
• The bindings provide information where the service is located.
• For SOAP protocol, the binding is <soap:binding>, and the transport is SOAP messages
on top of HTTP protocol.
56

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

• You can specify multiple bindings for a single portType.

The binding element has two attributes - the name attribute and the type attribute.

<binding name="Hello_Binding" type="tns:Hello_PortType">

The name attribute defines the name of the binding, and the type attribute points to the port for
the binding, in this case the "tns:Hello_PortType" port.

SOAP Binding

WSDL 1.1 includes built-in extensions for SOAP 1.1. This enables you to specify SOAPspecific
details, including SOAP headers, SOAP encoding styles, and the SOAPAction HTTP header.
The SOAP extension elements include:

This element indicates that the binding will be made available via SOAP. The styleattribute
indicates the overall style of the SOAP message format. A style value of rpc specifies an RPC
format.

The transport attribute indicates the transport of the SOAP messages. The value
http://schemas.xmlsoap.org/soap/http indicates the SOAP HTTP transport, whereas
http://schemas.xmlsoap.org/soap/smtp indicates the SOAP SMTP transport.

soap:operation

This element indicates the binding of a specific operation to a specific SOAP implementation.
The soapAction attribute specifies that the SOAPAction HTTP header be used for identifying the
service.

soap:body

This element enables you to specify the details of the input and output messages. In the case of
HelloWorld, the body element specifies the SOAP encoding style and the namespace URN
associated with the specified service.

Here is the piece of code from Example section:

<binding name="Hello_Binding" type="tns:Hello_PortType">


<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="sayHello">
<soap:operation soapAction="sayHello"/>
<input>
57

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</output>
</operation>
</binding>

WSDL Ports Element

A <port> element defines an individual endpoint by specifying a single address for a binding.

Here is the grammer to specify a port:

<wsdl:definitions ......>

<wsdl:service ...... > *

<wsdl:port name="nmtoken" binding="qname"> *

<-- extensibility element (1) -->

</wsdl:port>

</wsdl:service>

</wsdl:definitions>

• The port element has two attributes - the name attribute and the binding attribute.
• The name attribute provides a unique name among all ports defined within in the
enclosing WSDL document.
• The binding attribute refers to the binding using the linking rules defined by WSDL.
• Binding extensibility elements (1) are used to specify the address information for the
port.
• A port MUST NOT specify more than one address.
• A port MUST NOT specify any binding information other than address information.

58

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<service name="Hello_Service">

<documentation>WSDL File for HelloService</documentation>

<port binding="tns:Hello_Binding" name="Hello_Port">

<soap:address

location="http://www.examples.com/SayHello/">

</port>

</service>

WSDL Service Element

• The <service> element defines the ports supported by the Web service. For each of the
supported protocols, there is one port element. The service element is a collection of
ports.
• Web service clients can learn from the service element where to access the service,
through which port to access the Web service, and how the communication messages are
defined.
• The service element includes a documentation element to provide human-readable
documentation.

<service name="Hello_Service">

<documentation>WSDL File for HelloService</documentation>

<port binding="tns:Hello_Binding" name="Hello_Port">

<soap:address

location="http://www.examples.com/SayHello/">

</port>

</service>

The binding attributes of por element associate the address of the service with a binding element
defined in the Web service. In this example this is Hello_Binding

59

AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris

<binding name="Hello_Binding" type="tns:Hello_PortType">

<soap:binding style="rpc"

transport="http://schemas.xmlsoap.org/soap/http"/>

<operation name="sayHello">

<soap:operation soapAction="sayHello"/>

<input>

<soap:body

encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"

namespace="urn:examples:helloservice"

use="encoded"/>

</input>

<output>

<soap:body

encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"

namespace="urn:examples:helloservice"

use="encoded"/>

</output>

</operation>

</binding>

60

AP /CSE/COURSE MATERIAL

You might also like