IP-Unit 4 & 5
IP-Unit 4 & 5
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 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 ?>
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
<?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 a multiple-lines comment block
that spans over multiple
lines
*/
</body>
</html>
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>
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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
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");
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
10
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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
• 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;
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;
15
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
?>
</body>
</html>
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
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>
<?php
$i = 0;
17
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
</html>
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";
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
);
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>
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
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");
?>
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>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
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>
<?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>
<?php
function printMe($param = NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
26
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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);
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 />";
29
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>
30
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
31
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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
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
34
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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
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
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
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
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
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:
38
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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.
<?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.
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);
?>
<?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);
?>
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;
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
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'];
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>
<?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'];
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
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
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]>
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>
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
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
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 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.
PCDATA
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 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
example:
<!ELEMENT br EMPTY>
XML example:
<br />
Elements with only character data are declared with #PCDATA inside parentheses:
<!ELEMENT element-name (#PCDATA)>
example:
<!ELEMENT from (#PCDATA)>
Elements declared with the category keyword ANY, can contain any combination of parsable
data:
<!ELEMENT element-name ANY>
example:
<!ELEMENT note ANY>
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)>
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
XML example:
<payment type="check" />
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
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
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.
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;©right;</author>
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;©right;</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")
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)>
]>
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">
]>
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
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
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>
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
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: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>
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
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>
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>
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
Indicators
Order indicators:
• All
• Choice
• Sequence
Occurrence indicators:
• maxOccurs
• minOccurs
Group indicators:
• Group name
• attributeGroup name
Order Indicators
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
<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.
<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:schema>
Group Indicators
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: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>
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 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.
<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>
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.
<xs:attribute name="gender">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="male|female"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:schema>
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 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.
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.
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
• 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.
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>
79
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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>
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
81
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
• enumeration
• maxExclusive
• maxInclusive
• minExclusive
• minInclusive
• pattern
• whiteSpace
XSD Numeric Data Types
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.
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
• 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.
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
The XML DOM defines a standard for accessing and manipulating XML.
What is the DOM?
The DOM defines a standard for accessing documents like XML and HTML:
84
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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 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.
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 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".
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 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).
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
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.
Code explained:
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);
}
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.
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.
<script type="text/javascript">
90
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
xmlDoc=loadXMLDoc("books.xml");
</script>
</body>
</html>
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()
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);
</script>
</body>
</html>
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.
Methods are often referred to as something that is done (i.e. delete "book").
92
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
With the DOM, you can access every node in an XML document.
Accessing Nodes
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");
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
The length property defines the length of a node list (the number of nodes).
x=xmlDoc.getElementsByTagName("title");
for (i=0;i<x.length;i++)
{
document.write(x[i].childNodes[0].nodeValue);
document.write("<br />");
}
Example explained:
Node Types
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:
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;
}
Node Properties
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.
• nodeName
• nodeValue
• nodeType
• 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 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;
Example explained:
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:
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");
The following code fragment returns the text from the first <title> element in the node list
(x) :
txt=x[0].childNodes[0].nodeValue;
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;
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");
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
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
Often we want to loop an XML document, for example: when you want to extract the
value of each element.
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);
Output:
title: Everyday Italian
author: Giada De Laurentiis
year: 2005
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:
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:
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;
}
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.
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
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).
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;
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.
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");
Example explained:
Loop through all <book> elements and get their "category" attributes: Try it yourself
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;
Loop through all <book> elements and get their "category" attributes: Try it yourself
XML DOM Change Node Values
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).
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";
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.
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");
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";
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);
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);
x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];
x.removeChild(y);
108
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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:
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:
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:
x=xmlDoc.documentElement;
y=xmlDoc.getElementsByTagName("book")[0]
//replace the first book node with the new node
x.replaceChild(newNode,y);
110
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,8,"Easy");
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";
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
newel=xmlDoc.createElement("edition");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);
newatt=xmlDoc.createAttribute("edition");
newatt.nodeValue="first";
x=xmlDoc.getElementsByTagName("title");
x[0].setAttributeNode(newatt);
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
newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("first");
newel.appendChild(newtext);
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newComment);
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);
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);
If the second parameter of insertBefore() is null, the new node will be added after the last
existing child node.
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");
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 ");
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);
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
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
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
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
Property Description
length Returns the number of nodes in a node list
Method Description
item() Returns the node at the specified index in a node list
119
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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
121
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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
XML vocabularies:
<?xml version="1.0"?>
125
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<mrow>
<mn>2</mn>
<mo>+</mo>
<mn>3</mn>
<mo>=</mo>
<mn>5</mn>
</mrow>
</math>
</body>
</html>
126
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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
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.
• 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.
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.
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.
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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
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
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.
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
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
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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.
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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.
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.
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.
• 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.
10
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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:
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.
13
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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.
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");
We need to create an XMLHttpRequest, after that we will use few important functions like:
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:
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.
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.
<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;
} else if (window.ActiveXObject) { // IE
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 url="time.php?id="+rnd;
postRequest(url);
</script>
</head>
<body>
current date and time from server and shows on the form. To view the current
<form name="f1">
</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");
?>
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.
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>
22
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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
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>
</center>
</body>
</html>
25
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
}else{
echo "No";
}
?>
Output
26
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
<head>
<script language="javascript">
function postRequest(strURL){
var xmlHttp;
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
}
else{
function call_register(){
var password=document.reg.passwd.value;
postRequest(url);
</script>
</head>
<body>
<center>
<form name="reg">
<tr>
</tr>
<tr>
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
</tr>
<tr>
</tr>
<tr>
</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 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
The basic Web services platform is XML + HTTP. All the standard Web Services works
using following components
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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
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.
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.
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.
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.
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
34
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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.
• The first is to examine the individual roles of each web service actor.
• The second is to examine the emerging web service protocol stack.
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.
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.
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.
SOAP
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.
• 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
<?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
<?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: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.
Host: www.tutorialspoint.com
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">
...
...
</SOAP-ENV:Envelope>
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.
40
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
• 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>
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.
<?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.
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
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
<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.
The faultCode values defined below must be used in the faultcode element when describing
faults
Error
Description
SOAP-ENV:VersionMismatch
SOAP-ENV:MustUnderstand
An immediate child element of the Header element, with the mustUnderstand attribute set to "1",
was not understood
SOAP-ENV:Client
SOAP-ENV:Server
There was a problem with the server so the message could not proceed
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
<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
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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.
Host: www.xyz.org
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>
HTTP/1.0 200 OK
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:GetQuotationResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
47
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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:
<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.
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!".
<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>
<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
• 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.
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>
52
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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">
</message>
<message name="SayHelloResponse">
</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.
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.
<portType name="Hello_PortType">
<operation name="sayHello">
<input message="tns:SayHelloRequest"/>
<output message="tns:SayHelloResponse"/>
</operation>
</portType>
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:
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:
55
AP /CSE/COURSE MATERIAL
CS8651-Internet Programming-UNIT IV Notes-N. Mohammed Haris
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:
The service sends a message. The operation therefore has a single outputelement. Following is
the grammer for a notification operation:
• 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
The binding element has two attributes - the name attribute and the type attribute.
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.
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>
A <port> element defines an individual endpoint by specifying a single address for a binding.
<wsdl:definitions ......>
</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">
<soap:address
location="http://www.examples.com/SayHello/">
</port>
</service>
• 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">
<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
<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