0% found this document useful (0 votes)
85 views76 pages

Csdlo5012 Unit V Ip Notes

Uploaded by

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

Csdlo5012 Unit V Ip Notes

Uploaded by

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

PERI IT

PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

UNIT-IV
PHP and XML
An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in functions- Form
Validation- Regular Expressions - File handling – Cookies - Connecting to Database. 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).

An introduction to PHP
PHP is a server scripting language, and a powerful tool for making dynamic and interactive
Web pages.

What is PHP?
PHP is an acronym for "PHP: Hypertext Preprocessor"

 PHP is a widely-used, open source scripting language


 PHP scripts are executed on the server
 PHP is free to download and use

What is a PHP File?

 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, and the result is returned to the browser as plain
HTML
 PHP files have extension ".php"

What Can PHP Do?

 PHP can generate dynamic page content


 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

Why PHP?

 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)


 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side

Set Up PHP on Your Own PC


However, if your server does not support PHP, you must:

[Department of CSE] 1
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

 install a web server(Xampp)


 install a database, such as MySQL
 Run on web Browser

PHP 5 Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.

Basic PHP Syntax


A PHP script can be placed anywhere in the document. A PHP script starts
With <?php and ends with ?>,
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php". A PHP file normally contains HTML tags, and
some PHP scripting code.
Eg:
<!DOCTYPE html>
<html><body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body></html>

Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the program. Its only
purpose is to be read by someone who is looking at the code.
<!DOCTYPE html>
<html><body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/?>
</body></html>

[Department of CSE] 2
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

PHP Case Sensitivity


In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive.
Eg:<html><body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body></html>
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive,Others are case Sensitive
Eg:
<!DOCTYPE html>
<html><body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body></html>

PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_)
 Variable names are case-sensitive ($age and $AGE are two different variables)

In PHP, a variable starts with the $ sign, followed by the name of the variable:
Eg1:
<!DOCTYPE html>
<html><body>
<?php
$txt = "Hello world!";

[Department of CSE] 3
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body></html>

Eg2:
<!DOCTYPE html>
<html><body>
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
</body></html>
Eg:3
<!DOCTYPE html>
<html><body>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
</body></html>

PHP Variables Scope


In PHP, variables can be declared anywhere in the script.The scope of a variable is the part of
the script where the variable can be referenced/used.
PHP has three different variable scopes:

 local
 global
 static

Local Scope
A variable declared inside a function has a local scope and can only be accessed inside a
function:
Eg:

[Department of CSE] 4
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<body>
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
O/P:
Variable x inside function is:5
Variable x inside function is:0

Global Scope
A variable declared outside a function has a global scope and can only be accessed outside
a function:
Eg:
<html><body>
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body></html>

O/P:
Variable x inside function is:0
Variable x inside function is:5

PHP The global Keyword


The global keyword is used to access a global variable from within a function.To do this, use
the global keyword before the variables (inside the function):
Eg:
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;

[Department of CSE] 5
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
O/P: 15

PHP The static Keyword


Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.
EG:
<html><body>
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest(); //0
echo "<br>";
myTest(); //1
echo "<br>";
myTest(); //2
?>
</body></html

The PHP echo Statement


The echo statement can be used with or without parentheses: echo or echo().
Display Text
The following example shows how to output text with the echo command (notice that
the text can contain HTML markup):
EG:
<html><body>
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
</body></html>
Output:
PHP is Fun!
Hello world!

[Department of CSE] 6
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

I'm about to learn PHP!


This string was made with multiple parameters

PHP 5 Data Types


Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:

 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource
 A string is a sequence of characters, like "Hello world!".
PHP String:
Eg:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer is a whole number (without decimals). It is a number between -2,147,483,648
and +2,147,483,647.
Rules for integers:

 An integer must have at least one digit (0-9)


 An integer cannot contain comma or blanks
 An integer must not have a decimal point
 An integer can be either positive or negative

Eg:
<?php
$x = 5985;
var_dump($x);
?>
PHP Float
A float (floating point number) is a number with a decimal point or a number in
exponential form.

[Department of CSE] 7
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Eg:
<?php
$x = 10.365;
var_dump($x);
?>

PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;

PHP Array
An array stores multiple values in one single variable.
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>

PHP Object
An object is a data type which stores data and information on how to process that data.In
PHP, an object must be explicitly declared.
Eg:
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$a = new Car();
// show object properties
echo $a->model; //VW
?>
Program control
a)PHP Control Structures

Any PHP script is built out of a series of statements. A statement can be an assignment,
a function call, a loop, a conditional statement of even a statement that does nothing (an empty
statement). Statements usually end with a semicolon. In addition, statements can be grouped into
a statement-group by encapsulating a group of statements with curly braces. A statement-group is
a statement by itself as well.

[Department of CSE] 8
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

1). If Statement
2). Else Statement
3). Elseif Statement
4). Switch Statement

PHP - The if Statement


The if statement is used to execute some code only if a specified condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}

Eg:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>

PHP - The if...else Statement


Use the if....else statement to execute some code if a condition is true and another code
if the condition is false.

Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
EG:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

PHP - The if...elseif....else Statement


Use the if....elseif...else statement to specify a new condition to test, if the first condition is
false.

[Department of CSE] 9
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

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;
}

Eg:
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

The PHP switch Statement


Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

Eg:
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
[Department of CSE] 10
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
b)PHP Loops Control
Often when you write code, you want the same block of code to run over and over again
in a row. Instead of adding several almost equal code-lines in a script, we can use loops to
perform a task like this.
In PHP, we have the following looping statements:

 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

The PHP while Loop


The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}

Eg:
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
The PHP do...while Loop
The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
Syntax,
do {
code to be executed;
} while (condition is true);

[Department of CSE] 11
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Eg:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

The PHP for Loop


The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed;
}

Eg:
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

The PHP foreach Loop


The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax
foreach ($array as $value) {
code to be executed;
}
Eg:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>

PHP Array
What is an Array?
An array is a special variable, which can hold more than one value at a time.
Eg:
<!DOCTYPE html>
<html>
<body>
[Department of CSE] 12
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>

Output:Volvo,BMW,Toyota

PHP User Defined Functions


.A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads. A function will be executed by a call
to the function.
a)Create a User Defined Function in PHP
A user defined function declaration starts with the word "function":
Syntax
function functionName() {
code to be executed;
}
Eg:
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>

PHP Function Arguments


Information can be passed to functions through arguments. An argument is just like a
variable.Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just seperate them with a comma.

Eg:
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>

[Department of CSE] 13
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

B)PHP Built in Function


PHP comes standard with many functions and constructs. There are also functions that
require specific PHP extensions compiled in, otherwise fatal "undefined function" errors will
appear.

PHP functions:

 Array functions
 Calendar functions
 Date functions
 Directory functions
 Error functions
 Filesystem functions

a)Array Function
Some of the PHP Array Functions are,
PHP Count
The count() function is used to return the length (the number of elements) of an array:
Eg:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Output: 3

PHP - Sort Functions For Arrays


we will go through the following PHP array sort functions:

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order - sort()

Eg:

<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
Output:BMW,Toyoto,Volvo

[Department of CSE] 14
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Sort Array in Descending Order - rsort()


Eg:
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>
Output:Volvo,Toyoto,BMW

Sort Array (Ascending Order), According to Value - asort()

Eg:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>
Output:
Peter 35
Ben 37
Joe 43

Sort Array (Ascending Order), According to Key - ksort()


Eg:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>
Output:
Ben 37
Joe 43
Peter 35

Sort Array (Descending Order), According to Value - arsort()

Eg:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
output:
Joe 43
Ben 37
Peter 35

Sort Array (Descending Order), According to Key - krsort()


Eg:
<?php
[Department of CSE] 15
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");


krsort($age);
?>
output:
Peter 35
Joe 43
Ben 37

b)PHP Calendar Introduction


The calendar extension contains functions that simplifies converting between different
calendar formats.

PHP 5 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 specified calendar

cal_to_jd() Converts a date in a specified calendar 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, that the Easter Day is in a
specified year

Eg1: cal_from_jd() Function


<html><body>
<?php
$d=unixtojd(mktime(0,0,0,6,20,2007));
print_r(cal_from_jd($d,CAL_GREGORIAN));
?>
</body></html>
OUTPUT: Array ( [date] => 6/20/2007 [month] => 6 [day] => 20 [year] => 2007 [dow] => 3
[abbrevdayname] => Wed [dayname] => Wednesday [abbrevmonth] => Jun [monthname] =>
June )
Eg2: cal_from_jd
<html><body>

[Department of CSE] 16
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<?php
$d=cal_to_jd(CAL_GREGORIAN,6,20,2007);
echo $d;
?>
</body></html>
OUTPUT: 2454272

c)PHP Date/Time Introduction


The date/time functions allow you to get the date and time from the server where your
PHP script runs. You can then use the date/time functions to format the date and time in several
ways.
Date/Time Functions

Function Description

checkdate() Validates a Gregorian date

date_add() Adds days, months, years, hours, minutes, and seconds to a date

date_create_from_format() Returns a new DateTime object formatted according to a specified format

date_create() Returns a new DateTime object

date_date_set() Sets a new date

Eg1: checkdate()

<?php
var_dump(checkdate(12,31,-400));
echo "<br>";
var_dump(checkdate(2,29,2003));
echo "<br>";
var_dump(checkdate(2,29,2004));
?>
O/P: bool(false)
bool(false)
bool(true)
Eg2: date_create()
<?php
$date=date_create("2013-03-15");
date_add($date,date_interval_create_from_date_string("40 days"));
echo date_format($date,"Y-m-d");
?>
O/P: 2013-04-24

[Department of CSE] 17
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Eg: <?php
$date=date_create_from_format("j-M-Y","15-Mar-2013");
echo date_format($date,"Y/m/d");
?>
O/P: 2013/03/15

PHP Form Validation


The HTML form we will be working at in these chapters, contains various input fields:
required and optional text fields, radio buttons, and a submit button:
What is Validation ?

Validation means check the input submitted by the user. There are two types of validation are
available in PHP. They are as follows −

 Client-Side Validation − Validation is performed on the client machine web browsers.


 Server Side Validation − After submitted by data, The data has sent to a server and
perform validation checks in server machine.

Some of Validation rules for field

Validation Rules
Field

Name Should required letters and white-spaces

Email Should required @ and .

Website Should required a valid URL

Radio Must be selectable at least once

Check Box Must be checkable at least once

Drop Down menu Must be selectable at least once

Eg:
<html><body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);

[Department of CSE] 18
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

$email = test_input($_POST["email"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name"> <br><br>
E-mail: <input type="text" name="email"> <br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
?>
</body>
</html>

PHP REGULAR EXPRESSION


At its most basic level, a regex can be considered a method of pattern matching or
matching patterns within a string. In PHP the most oft used is PCRE or "Perl Compatible Regular
Expressions".
a) Matching starting string
Eg:
<?php
// create a string
$string = 'abcdefghijklmnopqrstuvwxyz0123456789';
echo preg_match("/abc/", $string);
?>
OUTPUTP:1
The code above will echo '1'. This is because it has found 1 match for the regex. That means it
has found the pattern 'abc' once in the larger string. preg_match() will count zero if there is no
matches.
b)Match beginning of a string
Now we wish to see if the string begins with abc. The regex character for beginning is the
caret ^. To see if our string begins with abc, we use it like this:
Eg:
<?php

[Department of CSE] 19
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

// create a string
$string = 'abcdefghijklmnopqrstuvwxyz0123456789';
// try to match the beginning of the string
if(preg_match("/^abc/", $string))
{
// if it matches we echo this line
echo 'The string begins with abc';
}
else
{
// if no match is found echo this line
echo 'No match found';
}
?>

c)Case Insensitive
If you used the above code to find the pattern ABC like this,if(preg_match("/^ABC/",
$string)) the script would have returned the message:No match found
EG: <?php
// create a string
$string = 'abcdefghijklmnopqrstuvwxyz0123456789';
// try to match our pattern
if(preg_match("/^ABC/i", $string))// specify i
{
// echo this is it matches
echo 'The string begins with abc';
}
else
{
// if not match is found echo this line
echo 'No match found';
}
?>
d)Find a pattern at the end of the string
This is done in much the same way as with finding a a pattern at the beginning of a
string. A common mistake made by many is to use the $ character to match the end of a string.
This is incorrect and \z should be used. Consider this. preg_match("/^foo$/", "foo\n")
Eg:
<?php
// create a string
$string = 'abcdefghijklmnopqrstuvwxyz0123456789';
// try to match our pattern at the end of the string
if(preg_match("/89\z/i", $string))
{
// if our pattern matches we echo this
echo 'The string ends with 89';

[Department of CSE] 20
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

}
else
{
// if no match is found we echo this line
echo 'No match found';
}
?>

e)Meta Characters
During our first look at regex we did some simple pattern matching. We also introduced
the caret(^) and the dollar($). These characters have special meaning. As we saw, the caret(^)
matched the beginning of a string and the dollar matched the end of a string. These characters,
along with others are called Meta characters. Here is a list of the Meta characters used for regex:

 . (Full stop)
 ^ (Carat)
 * (Asterix)
 + (Plus)
 ? (Question Mark)
 { (Opening curly brace)
 [ (Opening brace)
 ] (Closing brace)
 \ (Backslash)
 | (Pipe)
 ( (Opening parens)
 ) (Closing parens)
 } (Closing curly brace)

EG1:backslash
<?php
// create a string
$string = '1+1=2';
// try to match our pattern
if(preg_match("/^1\+1/i", $string))
{
// if the pattern matches we echo this
echo 'The string begins with 1+1';
}
else
{
// if no match is found we echo this line
echo 'No match found';
}
?>
OUTPUTP: The string begins with 1+1

[Department of CSE] 21
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Eg2:Opening and closing braces []


In a String a range seperated by a - symbol like:
Eg:
<?php
// create a string
$string = 'big';
// Search for a match
echo preg_match("/b[aoiu]g/", $string, $matches);
?>
OUTPUT: The above code will return 1

Eg3:Find [] brackect in a string


<?php
// create a string
$string = 'This is a [templateVar]';
// try to match our pattern
preg_match_all("/[\[\]]/", $string, $matches);
// loop through the matches with foreach
foreach($matches[0] as $value)
{
echo $value;
}
?>
OUTPUTP:[]
EG:Find a specific word with starting char and end char
<?php
// create a string
$string = 'six at noon taxes';
// look for a match
echo preg_match("/s.x/", $string, $matches);
?>
OUTPUT: 1
EG:Find a line with starting and ending character.
<?php
// create a string
$string = 'six'."\n".'at'."\n".'noon'."\n".'taxes'."\n";
// echo the string
echo nl2br($string);
// look for a match
echo preg_match_all("/\s/", $string, $matches);
?>

[Department of CSE] 22
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

OUTPUT:
The code above will return this:
six
at
noon
taxes
4
EG:Find for a match with pattern php in the string
<?php
// create a string
$string = 'pp';
// look for a match
echo preg_match("/ph+p/", $string, $matches);
?>
OUTPUT: 0
EG:Find a string with starting and ending letter separated by -?
<?php
// create a string
$string = '12345678';
// look for a match
echo preg_match("/1234-?5678/", $string, $matches);
?>
OUTPUT: 1
SPECIAL SEQUENCES
The backslash(\) is also used for sequences.

What are sequences?


Sequences are predefined sets of characters you can use in a class.

 \d - Matches any numeric character - same as [0-9]


 \D - Matches any non-numeric character - same as [^0-9]
 \s - Matches any whitespace character - sames as [ \t\n\r\f\v]
 \S - Matches any non-whitespace character - same as [^ \t\n\r\f\v]
 \w - Matches any alphanumeric character - same as [a-zA-Z0-9_]
 \W - Matches any non-alphanumeric character - same as [^a-zA-Z0-9_]

EG:Display a alphabet from a-z and A-Z and 0-9


<?php
// create a string
$string = 'ab-ce*fg@ hi & jkl(mnopqr)stu+vw?x yz0>1234<567890';
// match our pattern containing a special sequence
preg_match_all("/[\w]/", $string, $matches);
// loop through the matches with foreach

[Department of CSE] 23
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

foreach($matches[0] as $value)
{
echo $value;
}
?>
OUTPUT:abcefghijklmnopqrstuvwxyz0123456789

PHP File Handling

File handling is needed for any application. For some tasks to be done file needs to be
processed. File handling in PHP is similar as file handling is done by using any programming
language like C. PHP has many functions to work with normal files. Those functions are:

1) fopen() – PHP fopen() function is used to open a file. First parameter of fopen() contains name
of the file which is to be opened and second parameter tells about mode in which file needs to be
opened, e.g.,

<?php
$file = fopen(“demo.txt”,'w');
?>

Files can be opened in any of the following modes :

 “w” – Opens a file for write only. If file not exist then new file is created and if file
already exists then contents of file is erased.
 “r” – File is opened for read only.
 “a” – File is opened for write only. File pointer points to end of file. Existing data in file is
preserved.
 “w+” – Opens file for read and write. If file not exist then new file is created and if file
already exists then contents of file is erased.
 “r+” – File is opened for read/write.
 “a+” – File is opened for write/read. File pointer points to end of file. Existing data in file
is preserved. If file is not there then new file is created.
 “x” – New file is created for write only.

2) fread() –– After file is opened using fopen() the contents of data are read using fread(). It takes
two arguments. One is file pointer and another is file size in bytes,

E.g:
$filename = "demo.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );
$filedata = fread( $file, $size );
?>

[Department of CSE] 24
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

3) fwrite() – New file can be created or text can be appended to an existing file using fwrite()
function. Arguments for fwrite() function are file pointer and text that is to written to file. It can
contain optional third argument where length of text to written is specified, e.g.,
<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>

4) fclose() – file is closed using fclose() function. Its argument is file which needs to be closed,
E.G:
<?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>

PHP Overwriting

Now that "newfile.txt" contains some data we can show what happens when we open an
existing file for writing. All the existing data will be ERASED and we start with an empty file.

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

PHP File Upload


With PHP, it is easy to upload files to the server.
Create The HTML Form

Next, create an HTML form that allow users to choose the image file they want to upload:

<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
[Department of CSE] 25
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<input type="submit" value="Upload Image" name="submit">


</form>
</body>
</html>

Some rules to follow for the HTML form above:

 Make sure that the form uses method="post"


 The form also needs the following attribute: enctype="multipart/form-data". It specifies
which content-type to use when submitting the form

Without the requirements above, the file upload will not work.

Other things to notice:

 The type="file" attribute of the <input> tag shows the input field as a file-select control,
with a "Browse" button next to the input control

The form above sends data to a file called "upload.php", which we will create next.

Create The Upload File PHP Script

The "upload.php" file contains the code for uploading a file:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>

PHP script explained:

 $target_dir = "uploads/" - specifies the directory where the file is going to be placed
 $target_file specifies the path of the file to be uploaded

[Department of CSE] 26
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

 $uploadOk=1 is not used yet (will be used later)


 $imageFileType holds the file extension of the file (in lower case)
 Next, check if the image file is an actual image or a fake image

Limit File Size

The file input field in our HTML form above is named "fileToUpload".

Now, we want to check the size of the file. If the file is larger than 500KB, an error message is
displayed, and $uploadOk is set to 0:

// Check file size


if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
Limit File Type

The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types
gives an error message before setting $uploadOk to 0:

// Allow certain file formats


if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}

PHP 5 Cookies
A cookie is often used to identify a user.
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on
the user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax,
setcookie(name, value, expire, path, domain, secure, httponly);

PHP Create/Retrieve a Cookie


The following example creates a cookie named "user" with the value "John Doe". The
cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire
website (otherwise, select the directory you prefer). We then retrieve the value of the cookie
"user" (using the global variable $_COOKIE). We also use the isset() function to find out if the
cookie is set:

[Department of CSE] 27
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

EG:
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
OUTPUT: Cookie named 'user' is not set!

Modify a Cookie Value


To modify a cookie, just set (again) the cookie using the setcookie() function:
Example:
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
OUTPUT:
Cookie 'user' is set!
Value is: John Doe

[Department of CSE] 28
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past,

Eg:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>

Check if Cookies are Enabled


The following example creates a small script that checks whether cookies are
enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE
array variable:
Eg:
<!DOCTYPE html>
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
OUTPUT:Cookies are enabled.
DATABASE CONNECTION

MySQL Database

What is MySQL?

 MySQL is a database system used on the web


 MySQL is a database system that runs on a server

[Department of CSE] 29
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

 MySQL is ideal for both small and large applications


 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms

Database Queries
 A query is a question or a request.
 We can query a database for specific information and have a recordset returned.

a)Open a Connection to MySQL


Before we can access data in the MySQL database, we need to be able to connect to the
server,
Two type of DBConnection are
1)DB Connection by Object-oriented
2)DB Connection by Procedural

a) DB Connection- MySQLi Object-Oriented

Eg:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

b)Create a MySQL Database Using MySQLi and PDO


The CREATE DATABASE statement is used to create a database in MySQL.
The following examples create a database named "myDB":
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
[Department of CSE] 30
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
echo "Connected successfully";
?>

c)Create a MySQL Table Using MySQLi and PDO


The CREATE TABLE statement is used to create a table in MySQL.
We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname",
"email" and "reg_date":
Eg:
CREATE TABLE MyGuests (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),reg_date TIMESTAMP);

d)Insert Data Into MySQL Using MySQLi and PDO


After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:

 The SQL query must be quoted in PHP


 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
EG:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);

[Department of CSE] 31
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

}
//Insert values into table
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

e)Select Data From a MySQL Database


The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name;
or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name;
Eg:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//display the result
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

[Department of CSE] 32
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

f)Delete Data From a MySQL Table Using MySQLi


The DELETE statement is used to delete records from a table:
DELETE FROM table_name WHERE some_column = value;
Let's look at the "MyGuests" table:

id firstname lastname email reg_date

1 John Doe [email protected] 2014-10-22 14:26:15

2 Mary Moe [email protected] 2014-10-23 10:22:30

3 Julie Dooley [email protected] 2014-10-26 10:48:23

EG:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>

g)Update Data In a MySQL Table Using MySQLi


The UPDATE statement is used to update existing records in a table:
[Department of CSE] 33
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

UPDATE table_name SET column1=value, column2=value2,...WHERE some_column=value ;

id firstname lastname email reg_date

1 John Doe [email protected] 2014-10-22 14:26:15

2 Mary Moe [email protected] 2014-10-23 10:22:30

EG:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";


if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
LIBRARY MANAGEMENT MANAGEMENT USING PHP FORMS
lib.html
<html>
<head>
<title>LIBRARY MANAGEMENT</title></head>
<body>
<form action="connect1.php" method="post">
<p>Enter the book number:<input type="text" name="bid"></p>
<p>Enter the book name:&nbsp&nbsp <input type="text" name="bname"></p>
<p>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="submit" name="OK"></p>
</form>
</body>
</html>

[Department of CSE] 34
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

connect1.php
<?php
$bid=$_POST['bid'];
$bname=$_POST['bname'];
$con=@mysql_connect("localhost","root","")or die(mysql-error());
echo "connected to database";
$db=@mysql_select_db("student",$con)or die(mysql-error());
echo "selected database";
$str="insert into book values($bid,'$bname')";
$res=@mysql_query($str)or die(mysql-error());
if($res>0)
{
echo "record created";
}
?>

XML BASICS:
Introduction to XML

What is XML?

 XML stands for eXtensible Markup Language


 XML is a markup language much like HTML
 XML was designed to store and transport data
 XML was designed to be self-descriptive
 XML is a W3C Recommendation

1)XML Separates Data from Presentation


2)XML does not carry any information about how to be displayed.
3)The same XML data can be used in many different presentation scenarios.
4) with XML, there is a full separation between data and presentation.

Eg:

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

1.XML Does Not Use Predefined Tags


2.The XML language has no predefined tags.
3.The tags in the example above (like <to> and <from>) are not defined in any XML standard.
4.These tags are "invented" by the author of the XML document.
5.HTML works with predefined tags like <p>, <h1>, <table>, etc.
[Department of CSE] 35
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

6.With XML, the author must define both the tags and the document structure.
XML is Extensible

Most XML applications will work as expected even if new data is added (or removed).

<note>
<date>2015-09-01</date>
<hour>08:30</hour>
<to>Adam</to>
<from>Jill</from>
<body>I will be home late</body>
</note>

XML Simplifies Things


1.It simplifies data sharing
2.It simplifies data transport
3.It simplifies platform changes
4.It simplifies data availability

Many computer systems contain data in incompatible formats. Exchange data between
incompatible systems (or upgraded systems), is a time-consuming tasks for web developers Large
amounts of data must be converted, and incompatible data is often lost.

XML stores data in plain text format. This provides a software- and hardware-independent way
of storing, transporting, and sharing data.

XML also makes it easier to expand or upgrade to new operating systems, new applications, or
new browsers, without losing data.

With XML, data can be available to all kinds of "reading machines" like people, computers, voice
machines, news feeds, etc.

XML Separates Data from HTML

When displaying XML data in HTML, you do not have to edit the HTML file when the data
changes.

With XML, data can be stored in separate XML files.

With a few lines of JavaScript code, you can read an XML file and update the data content of any
HTML page.

This example loops through all <CD> elements in an XML file, and display the values of
<ARTIST> and <TITLE> elements in an HTML table:

[Department of CSE] 36
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

XML Tree

XML documents form a tree structure that starts at "the root" and branches to "the leaves"
An Example XML Document
XML documents use a self-describing and simple syntax:

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


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

XML Documents Form a Tree Structure

 All XML documents must contain a root element. This is "the parent" of all other
elements.
 The elements in an XML document form a document tree. The tree starts at the root and
branches to the lowest level of the tree.
 All elements can have sub elements (child elements):
 The terms parent, child, and sibling are used to describe the relationships between
elements.
 Parent elements have children.
 Children on the same level are called siblings (brothers or sisters).
 All elements can have text content and attributes (just like in HTML).

XML Tree Structure

[Department of CSE] 37
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Eg:

<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</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">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

The root element in the example is <bookstore>.


All <book> elements in the document are contained within <bookstore>.
The <book> element has 4 children: <title>,< author>, <year>, <price>.

XML Syntax Rules

The syntax rules of XML are very simple and logical. The rules are easy to learn, and easy to use.

All XML Elements Must Have a Closing Tag

In HTML, some elements do not have to have a closing tag:


<p>This is a paragraph.<br>
In XML, it is illegal to omit the closing tag. All elements must have a closing tag:
<p>This is a paragraph.</p><br />

Note: You might have noticed the XML declaration did not have a closing tag. This is not an
error. The declaration is not a part of the XML document itself.

XML Tags are Case Sensitive

XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.
Opening and closing tags must be written with the same case:
[Department of CSE] 38
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<Message>This is incorrect</message>
<message>This is correct</message>

Note: "Opening and closing tags" are often referred to as "Start and end tags". Use whatever you
prefer. It is exactly the same thing.

XML Elements Must be Properly Nested

In HTML, you might see improperly nested elements:


<b><i>This text is bold and italic</b></i>

NOTE:Refer Class Notes for below rule set with example.

Other Rule Set are


1. XML Documents Must Have a Root Element
2.XML Attribute Values Must be Quoted
3.Entity References
4.Comments in XML
XML Elements
What is an XML Element?
An XML element is everything from (including) the element's start tag to (including) the
element's end tag.

An element can contain:

 text
 attributes
 other elements
 or a mix of the above

Eg:<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

[Department of CSE] 39
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Eg:
<title>, <author>, <year>, and <price> have text content because they contain text.
<bookstore> and <book> have element contents, because they contain other elements.
<book> has an attribute (category="CHILDREN").

Empty XML Elements


An element with no content is said to be empty.
In XML, you can indicate an empty element like this:
<element></element>

XML Naming Rules


XML elements must follow these naming rules:

 Element names are case-sensitive


 Element names must start with a letter or underscore
 Element names cannot start with the letters xml (or XML, or Xml, etc)
 Element names can contain letters, digits, hyphens, underscores, and periods
 Element names cannot contain spaces

Any name can be used, no words are reserved (except xml).

Naming Styles
There are no naming styles defined for XML elements. But here are some commonly used:

Style Example Description

Lower case <firstname> All letters lower case

Upper case <FIRSTNAME> All letters upper case

Underscore <first_name> Underscore separates words

Pascal case <FirstName> Uppercase first letter in each word

Camel case <firstName> Uppercase first letter in each word except the
first

XML documents often have a corresponding database. A good practice is to use the naming
rules of your database for the elements in the XML documents.

[Department of CSE] 40
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

XML Attributes

1.XML elements can have attributes, just like HTML.


2.Attributes are designed to contain data related to a specific element.
3.XML Attributes Must be Quoted
4.Attribute values must always be quoted. Either single or double quotes can be used.

For a person's gender, the <person> element can be written like this:
<person gender="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

XML Namespaces
XML Namespaces provide a method to avoid element name conflicts.
Name Conflicts
In XML, element names are defined by the developer. This often results in a conflict when
trying to mix XML documents from different XML applications.
This XML carries HTML table information:
Eg:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
This XML carries information about a table (a piece of furniture):
<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>

If these XML fragments were added together, there would be a name conflict. Both contain
a <table> element, but the elements have different content and meaning.A user or an XML
application will not know how to handle these differences.

Solving the Name Conflict Using a Prefix


Name conflicts in XML can easily be avoided using a name prefix.This XML carries
information about an HTML table, and a piece of furniture:
Eg:
<h:table>

[Department of CSE] 41
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>

<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
XML Document Types

An XML document with correct syntax is called "Well Formed".


A "Valid" XML document must also conform to a document type definition.

Well Formed XML Documents


An XML document with correct syntax is "Well Formed".
The syntax rules were described in the previous chapters:

 XML documents must have a root element


 XML elements must have a closing tag
 XML tags are case sensitive
 XML elements must be properly nested
 XML attribute values must be quoted

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


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

XML Validator
This help to check the syntax of your XML files, we have Valid XML Documents

A "valid" XML document is not the same as a "well formed" XML document.
A "valid" XML document must be well formed. In addition it must conform to a document type
definition.Rules that defines the legal elements and attributes for XML documents are called
Document Type Definitions (DTD) or XML Schemas.
There are two different document type definitions that can be used with XML:

 DTD - The original Document Type Definition


 XML Schema - An XML-based alternative to DTD

[Department of CSE] 42
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

When to Use a DTD/Schema?


With a DTD, independent groups of people can agree to use a standard DTD for
interchanging data.
XML DTD
The purpose of a DTD is to define the structure of an XML document. It defines the
structure with a list of legal elements:

<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>

The DTD above is interpreted like this:

 !DOCTYPE note defines that the root element of the document is note
 !ELEMENT note defines that the note element must contain the elements: "to, from,
heading, body"
 !ELEMENT to defines the to element to be of type "#PCDATA"
 !ELEMENT from defines the from element to be of type "#PCDATA"
 !ELEMENT heading defines the heading element to be of type "#PCDATA"
 !ELEMENT body defines the body element to be of type "#PCDATA"

Using DTD for Entity Declaration


A doctype declaration can also be used to define special characters and character strings,
used in the document:

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


<!DOCTYPE note [
<!ENTITY nbsp "&#xA0;">
<!ENTITY writer "Writer: Donald Duck.">
<!ENTITY copyright "Copyright: W3Schools.">
]>

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer;&nbsp;&copyright;</footer>
</note>

[Department of CSE] 43
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Why Use a DTD?


With a DTD, independent groups of people can agree on a standard for interchanging
data.With a DTD, you can verify that the data you receive from the outside world is valid.

NOTE:Refer class notes for more details

XML Schema
An XML Schema describes the structure of an XML document, just like a DTD.
An XML document with correct syntax is called "Well Formed".
An XML document validated against an XML Schema is both "Well Formed" and "Valid".
XML Schema
XML Schema is an XML-based alternative to DTD:

<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

The Schema above is interpreted like this:

 <xs:element name="note"> defines the element called "note"


 <xs:complexType> the "note" element is a complex type
 <xs:sequence> the complex type is a sequence of elements
 <xs:element name="to" type="xs:string"> the element "to" is of type string (text)
 <xs:element name="from" type="xs:string"> the element "from" is of type string
 <xs:element name="heading" type="xs:string"> the element "heading" is of type string
 <xs:element name="body" type="xs:string"> the element "body" is of type string

XML Schemas are More Powerful than DTD

1.XML Schemas are written in XML


2.XML Schemas are extensible to additions
3.XML Schemas support data types
4.XML Schemas support namespaces

Why Use an XML Schema?


1. With XML Schema, your XML files can carry a description of its own format.
2. With XML Schema, independent groups of people can agree on a standard for
interchanging data.
3.With XML Schema, you can verify data.
[Department of CSE] 44
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

XML Schemas Support Data Types


One of the greatest strength of XML Schemas is the support for data types:

 It is easier to describe document content


 It is easier to define restrictions on data
 It is easier to validate the correctness of data
 It is easier to convert data between different data types

XML Schemas use XML Syntax

Another great strength about XML Schemas is that they are written in XML:

 You don't have to learn a new language


 You can use your XML editor to edit your Schema files
 You can use your XML parser to parse your Schema files
 You can manipulate your Schemas with the XML DOM
 You can transform your Schemas with XSLT

XML DOM
What is the XML DOM?

 A standard object model for XML


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

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

XML DOM Nodes


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

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

The DOM says:

 The entire document is a document node


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

[Department of CSE] 45
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

DOM Example

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


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

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

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

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

[Department of CSE] 46
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Text is Always Stored in Text Nodes

A common error in DOM processing is to expect an element node to contain text.

However, the text of an element node is stored in a text node.


In this example: <year>2005</year>, the element node <year>, holds a text node with the value
"2005"."2005" is not the value of the <year> element!

The XML DOM Node Tree

The XML DOM views an XML document as a tree-structure. The tree structure is called
a node-tree. All 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:

Node Parents, Children, and Siblings

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

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

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


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

[Department of CSE] 47
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

XML DOM Traverse Node Tree


Traversing means looping through or traveling across the node tree.
Traversing the Node Tree
Often you want to loop an XML document, for example: when you want to extract the
value of each element.

This is called "Traversing the node tree"

The example below loops through all child nodes of <book>, and displays their names and values:

<html>
<head>
<script src="loadxmlstring.js"></script>
</head>
<body>
<script>
var text="<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
var xmlDoc=loadXMLString(text);
// documentElement always represents the root node
var x=xmlDoc.documentElement.childNodes;

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

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

Example explained:

1. Load the XML string into xmlDoc


2. Get the child nodes of the root element

[Department of CSE] 48
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

3. For each child node, output the node name and the node value of the text node

NOTE:Refer:Examples from class notes

XML DOM Change Node Values

1.The nodeValue property is used to change a node value.


2.The setAttribute() method is used to change an attribute value.
3.Change the Value of an Element

In the DOM, everything is a node. Element nodes do not have a text value.The text of an
element node is stored in a child node. This node is called a text node.The way to change the text
of an element, is to change the value of the child node (text node).

Change the Value of a Text Node


The nodeValue property can be used to change the value of a text node.
The following code changes the text node value of the first <title> element:

Eg:books.xml

<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</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>

[Department of CSE] 49
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

Test.html
<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js">
</script>
</head>
<body>
<script>
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";
document.write(x.nodeValue);
</script>
</body>
</html>

Example explained:

1. Load "books.xml" into xmlDoc


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

Change the Value of an Attribute


In the DOM, attributes are nodes. Unlike element nodes, attribute nodes have text
values.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.

test1.html

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js">
</script>
</head>
<body>
<script>
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("category","food");

[Department of CSE] 50
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

document.write(x[0].getAttribute("category"));
</script>
</body>
</html>

output:
food

XML DOM Remove Nodes

1.The removeChild() method removes a specified node.


2.The removeAttribute() method removes a specified attribute.
3.Remove an Element Node
4.The removeChild() method removes a specified node.
5.When a node is removed, all its child nodes are also removed.

The following code fragment will remove the first <book> element from the loaded xml:

test2.html

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js">
</script>
</head>
<body>
<script>
xmlDoc = loadXMLDoc("books.xml");
root = xmlDoc.documentElement;
currNode = root.childNodes[1];
removedNode = currNode.removeChild(currNode.childNodes[1]);
document.write("Removed node: " + removedNode.nodeName);
</script>
</body>
</html>

Output:
Removed node: title

XML DOM Replace Nodes

1.The replaceChild() method replaces a specified node.


2.The nodeValue property replaces text in a text node.

[Department of CSE] 51
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

test3.html

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js">
</script>
</head>
<body>
<script>
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.documentElement;
//create a book element, title element and a text node
newNode=xmlDoc.createElement("book");
newTitle=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("A Notebook");
//add the text node to the title node,
newTitle.appendChild(newText);
//add the title node to the book node
newNode.appendChild(newTitle);
y=xmlDoc.getElementsByTagName("book")[0]
//replace the first book node with the new node
x.replaceChild(newNode,y);

z=xmlDoc.getElementsByTagName("title");
for (i=0;i<z.length;i++)
{
document.write(z[i].childNodes[0].nodeValue);
document.write("<br>");
}
</script>
</body>
</html>

Output:
A Notebook
Harry Potter
XQuery Kick Start
Learning XML

Presenting XML document


Display XML Data in an HTML Table

This example loops through each <CD> element, and display the values of the <ARTIST> and
the <TITLE> elements in an HTML table:
[Department of CSE] 52
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<!DOCTYPE html>
<html>
<style>
table,th,td
{
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<table id="demo"></table>
<script>
var x,i,xmlhttp,xmlDoc,table;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "cd_catalog.xml", false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName("CD");
table="<tr><th>Artist</th><th>Title</th></tr>";
for (i = 0; i <x.length; i++)
{
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue + "</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "</td></tr>";
}
document.getElementById("demo").innerHTML = table;
</script>
</body>
</html>

Eg:Refere class notes example(xml with external dtd and cascading style sheet)

XML DOM Parser

All major browsers have a built-in XML parser to read and manipulate XML.The XML parser
converts XML into an XML DOM object that can be accessed with JavaScript.

XML Parser

The XML DOM contains methods 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.

[Department of CSE] 53
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

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

Most browsers have a built-in XML parser.

Load an XML Document

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

<!DOCTYPE html>
<html>
<body>
<script>
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // for IE 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","books.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML;
document.write("XML document loaded into an XML DOM Object.");
</script>
</body>
</html>
Output:
XML document loaded into an XML DOM Object.

Code explained:

 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

Load an XML String

The following code loads and parses an XML string:

<!DOCTYPE html>
<html>
<body>
<script>

[Department of CSE] 54
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

text="<bookstore><book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book></bookstore>";
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(text);
}
document.write("XML string is loaded into an XML DOM Object");
</script>
</body>
</html>
Output:
XML string is loaded into an XML DOM Object

PCDATA - Parsed Character Data

XML parsers normally parse all the text in an XML document.When an XML element is
parsed, the text between the XML tags is also parsed:
<message>This text is also parsed</message>

CDATA - (Unparsed) Character Data

The term CDATA is used about text data that should not be parsed by the XML parser.

Characters like "<" and "&" are illegal in XML elements."<" will generate an error because the
parser interprets it as the start of a new element."&" will generate an error because the parser
interprets it as the start of an character entity.

Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script
code can be defined as CDATA.Everything inside a CDATA section is ignored by the parser.

A CDATA section starts with "<![CDATA[" and ends with "]]>":

<script>
<![CDATA[
function matchwo(a,b)
{
[Department of CSE] 55
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

if (a < b && a < 0) then


{
return 1;
}
else
{
return 0;
}
}
]]>
</script>
In the example above, everything inside the CDATA section is ignored by the parser.

Notes on CDATA sections:

A CDATA section cannot contain the string "]]>". Nested CDATA sections are not allowed.
The "]]>" that marks the end of the CDATA section cannot contain spaces or line breaks.

What is XML Parsing?

Parsing XML refers to going through XML document to access data or to modify data in one or
other way.

What is XML Parser?

XML Parser provides way how to access or modify data present in an XML document. Java
provides multiple options to parse XML document. Following are various types of parsers which
are commonly used to parse XML documents.

 Dom Parser - Parses the document by loading the complete contents of the document and
creating its complete hiearchical tree in memory.
 SAX Parser - Parses the document on event based triggers. Does not load the complete
document into the memory.

a)Java DOM Parser

The Document Object Model is an official recommendation of the World Wide Web Consortium
(W3C). It defines an interface that enables programs to access and update the style, structure,and
contents of XML documents. XML parsers that support the DOM implement that interface.

When to use?

You should use a DOM parser when:

 You need to know a lot about the structure of a document

[Department of CSE] 56
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

 You need to move parts of the document around (you might want to sort certain elements,
for example)
 You need to use the information in the document more than once

Advantages

The DOM is a common interface for manipulating document structures. One of its design goals is
that Java code written for one DOM-compliant parser should run on any other DOM-compliant
parser without changes.

DOM interfaces

The DOM defines several Java interfaces. Here are the most common interfaces:

 Node - The base datatype of the DOM.


 Element - The vast majority of the objects you'll deal with are Elements.
 Attr Represents an attribute of an element.
 Text The actual content of an Element or Attr.
 Document Represents the entire XML document. A Document object is often referred to
as a DOM tree.

Common DOM methods

When you are working with the DOM, there are several methods you'll use often:

 Document.getDocumentElement() - Returns the root element of the document.


 Node.getFirstChild() - Returns the first child of a given Node.
 Node.getLastChild() - Returns the last child of a given Node.
 Node.getNextSibling() - These methods return the next sibling of a given Node.
 Node.getPreviousSibling() - These methods return the previous sibling of a given Node.
 Node.getAttribute(attrName) - For a given Node, returns the attribute with the requested
name.

Eg1:Displaying xml data


Input.xml
<?xml version="1.0"?>
<class>
<student rollno="393">
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
[Department of CSE] 57
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<marks>90</marks>
</student>
</class>

DomParserDemo.java

package com.tutorialspoint.xml;

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class DomParserDemo {


public static void main(String[] args){

try {
File inputFile = new File("input.txt");
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("student");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :"
+ nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Student roll no : " + eElement.getAttribute("rollno"));
System.out.println("First Name : "
[Department of CSE] 58
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

+ eElement.getElementsByTagName("firstname")
.item(0).getTextContent());
System.out.println("Last Name : "
+ eElement.getElementsByTagName("lastname")
.item(0).getTextContent());
System.out.println("Nick Name : "
+ eElement.getElementsByTagName("nickname").item(0)
.getTextContent());
System.out.println("Marks : "
+ eElement.getElementsByTagName("marks").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output:
Root element :class
----------------------------

Current Element :student


Student roll no : 393
First Name : dinkar
Last Name : kad
Nick Name : dinkar
Marks : 85

Current Element :student


Student roll no : 493
First Name : Vaneet
Last Name : Gupta
Nick Name : vinni
Marks : 95

Current Element :student


Student roll no : 593
First Name : jasvir
Last Name : singn
Nick Name : jazz
Marks : 90

Eg2:Java DOM Parser - Modify XML Document


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

[Department of CSE] 59
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<supercars company="Ferrari">
<carname type="formula one">Ferrari 101</carname>
<carname type="sports">Ferrari 202</carname>
</supercars>
<luxurycars company="Benteley">
<carname>Benteley 1</carname>
<carname>Benteley 2</carname>
<carname>Benteley 3</carname>
</luxurycars>
</cars>

package com.tutorialspoint.xml;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ModifyXmlFileDemo {

public static void main(String argv[]) {

try {
File inputFile = new File("input.xml");
DocumentBuilderFactory docFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder =
docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(inputFile);
Node cars = doc.getFirstChild();
Node supercar = doc.getElementsByTagName("supercars").item(0);
// update supercar attribute
NamedNodeMap attr = supercar.getAttributes();
Node nodeAttr = attr.getNamedItem("company");
nodeAttr.setTextContent("Lamborigini");

// loop the supercar child node


NodeList list = supercar.getChildNodes();
[Department of CSE] 60
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

for (int temp = 0; temp < list.getLength(); temp++) {


Node node = list.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) node;
if ("carname".equals(eElement.getNodeName())){
if("Ferrari 101".equals(eElement.getTextContent())){
eElement.setTextContent("Lamborigini 001");
}
if("Ferrari 202".equals(eElement.getTextContent()))
eElement.setTextContent("Lamborigini 002");
}
}
}
NodeList childNodes = cars.getChildNodes();
for(int count = 0; count < childNodes.getLength(); count++){
Node node = childNodes.item(count);
if("luxurycars".equals(node.getNodeName()))
cars.removeChild(node);
}
// write the content on console
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
System.out.println("-----------Modified File-----------");
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, consoleResult);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
-----------Modified File-----------
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars>
<supercars company="Lamborigini">
<carname type="formula one">Lamborigini 001</carname>
<carname type="sports">Lamborigini 002</carname>
</supercars></cars>

b)Java SAX Parser

SAX (the Simple API for XML) is an event-based parser for xml documents.Unlike a DOM
parser, a SAX parser creates no parse tree. SAX is a streaming interface for XML, which means
that applications using SAX receive event notifications about the XML document being processed
[Department of CSE] 61
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

an element, and attribute, at a time in sequential order starting at the top of the document, and
ending with the closing of the ROOT element.

 Reads an XML document from top to bottom, recognizing the tokens that make up a well-
formed XML document
 Tokens are processed in the same order that they appear in the document
 Reports the application program the nature of tokens that the parser has encountered as
they occur
 The application program provides an "event" handler that must be registered with the
parser
 As the tokens are identified, callback methods in the handler are invoked with the relevant
information

When to use?

You should use a SAX parser when:

 You can process the XML document in a linear fashion from the top down
 The document is not deeply nested
 You are processing a very large XML document whose DOM tree would consume too
much memory.Typical DOM implementations use ten bytes of memory to represent one
byte of XML
 The problem to be solved involves only part of the XML document
 Data is available as soon as it is seen by the parser, so SAX works well for an XML
document that arrives over a stream

Disadvantages of SAX

 We have no random access to an XML document since it is processed in a forward-only


manner
 If you need to keep track of data the parser has seen or change the order of items, you
must write the code and store the data on your own

ContentHandler Interface

This interface specifies the callback methods that the SAX parser uses to notify an application
program of the components of the XML document that it has seen.

 void startDocument() - Called at the beginning of a document.


 void endDocument() - Called at the end of a document.
 void startElement(String uri, String localName, String qName, Attributes atts) -
Called at the beginning of an element.
 void endElement(String uri, String localName,String qName) - Called at the end of an
element.
 void characters(char[] ch, int start, int length) - Called when character data is
encountered.

[Department of CSE] 62
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

 void ignorableWhitespace( char[] ch, int start, int length) - Called when a DTD is
present and ignorable whitespace is encountered.
 void processingInstruction(String target, String data) - Called when a processing
instruction is recognized.
 void setDocumentLocator(Locator locator)) - Provides a Locator that can be used to
identify positions in the document.
 void skippedEntity(String name) - Called when an unresolved entity is encountered.
 void startPrefixMapping(String prefix, String uri) - Called when a new namespace
mapping is defined.
 void endPrefixMapping(String prefix) - Called when a namespace definition ends its
scope.

Attributes Interface

This interface specifies methods for processing the attributes connected to an element.

 int getLength() - Returns number of attributes.


 String getQName(int index)
 String getValue(int index)
 String getValue(String qname)

Eg:Displaying XML Data using SAX PArser


Input.xml
<?xml version="1.0"?>
<class>
<student rollno="393">
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<marks>90</marks>
</student>
</class>

[Department of CSE] 63
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

SAXParserDemo.java
package com.tutorialspoint.xml;

import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXParserDemo {


public static void main(String[] args){

try {
File inputFile = new File("input.txt");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
UserHandler userhandler = new UserHandler();
saxParser.parse(inputFile, userhandler);
} catch (Exception e) {
e.printStackTrace();
}
}
}

class UserHandler extends DefaultHandler {

boolean bFirstName = false;


boolean bLastName = false;
boolean bNickName = false;
boolean bMarks = false;

@Override
public void startElement(String uri,
String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("student")) {
String rollNo = attributes.getValue("rollno");
System.out.println("Roll No : " + rollNo);
} else if (qName.equalsIgnoreCase("firstname")) {
bFirstName = true;
} else if (qName.equalsIgnoreCase("lastname")) {
bLastName = true;
} else if (qName.equalsIgnoreCase("nickname")) {
bNickName = true;
[Department of CSE] 64
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

}
else if (qName.equalsIgnoreCase("marks")) {
bMarks = true;
}
}

@Override
public void endElement(String uri,
String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("student")) {
System.out.println("End Element :" + qName);
}
}

@Override
public void characters(char ch[],
int start, int length) throws SAXException {
if (bFirstName) {
System.out.println("First Name: "+ new String(ch, start, length));
bFirstName = false;
} else if (bLastName) {
System.out.println("Last Name: " + new String(ch, start, length));
bLastName = false;
} else if (bNickName) {
System.out.println("Nick Name: " + new String(ch, start, length));
bNickName = false;
} else if (bMarks) {
System.out.println("Marks: " + new String(ch, start, length));
bMarks = false;
}
}
}
Output:
Roll No : 393
First Name: dinkar
Last Name: kad
Nick Name: dinkar
Marks: 85
End Element :student
Roll No : 493
First Name: Vaneet
Last Name: Gupta
Nick Name: vinni
Marks: 95
End Element :student
Roll No : 593
[Department of CSE] 65
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

First Name: jasvir


Last Name: singn
Nick Name: jazz
Marks: 90
End Element :student

XML Validator
XML validator will stop execution if syntax error found in the .XML file ie..,Errors in XML
documents will stop your XML applications.

The W3C XML specification states that a program should stop processing an XML document
if it finds an error. The reason is that XML software should be small, fast, and compatible. HTML
browsers are allowed to display HTML documents with errors (like missing end tags).

With XML, errors are not allowed.

Syntax-Check Your XML


To help you syntax-check your XML, we have created an XML validator.
Eg1:

Try to validate correct XML :


<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Eg2:
Try to validate incorrect XML :
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</pheading>
<body>Don't forget me this weekend!</body>
</note>

XSL

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

[Department of CSE] 66
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Need for XSL

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

Following are the main parts of XSL −

 XSLT − used to transform XML document into various other types of document.
 XPath − used to navigate XML document.
 XSL-FO − used to format XML document.

What is XSLT

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

How XSLT Works

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

Advantages

Here are the advantages of using XSLT −

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


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

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

Students.xml
<?xml version = "1.0"?>
<class>

[Department of CSE] 67
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<student rollno = "393">


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

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

 Page should have a title Students.


 Page should have a table of student details.
 Columns should have following headers: Roll No, First Name, Last Name, Nick Name,
Marks
 Table must contain details of the students accordingly.

Step 1: Create XSLT document

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

students.xsl

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


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

<html>
<body>
<h2>Students</h2>

<table border = "1">

[Department of CSE] 68
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<tr bgcolor = "#9acd32">


<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>

<!-- for-each processing instruction


Looks for each element matching the XPath expression
-->

<xsl:for-each select="class/student">
<tr>
<td>
<!-- value-of processing instruction
process the value of the element matching the XPath expression
-->
<xsl:value-of select = "@rollno"/>
</td>

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


<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "marks"/></td>

</tr>
</xsl:for-each>

</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Step 2: Link the XSLT Document to the XML Document

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

<?xml version = "1.0"?>


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

[Department of CSE] 69
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Step 3: View the XML Document in Internet Explorer

students.xml

<?xml version = "1.0"?>


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

[Department of CSE] 70
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Atom and RSS News Feeds


A news feed provides a way to access the content of a web site without looking at its web
pages. The format of the news feed can be one of several types including Atom, RSS and XML.
Services take the feed in any recognised format and re-serve it with enhancements compatible
with any news reader.

When you subscribe to a news feed with a news reader you will receive the content in a
way that is very similar to email. When you launch your news reader software it will check your
subscriptions and fetch any new content. This will usually contain information such as the date
and headline, author, article summary and a web link to the source article as a web page. It can
also be used to embed media files such as podcasts, streaming radio and video.

The strength of using a news feed comes from how it is managed and customised. As a
subscriber you are free to assemble as many news feeds as you like. And you can choose to use
only the sources that interest you. For example you could choose to subscribe to the Technology
section If you use a web browser such as Firefox you can also subscribe to news feeds as
Live Bookmarks. With Live Bookmarks you will see the item titles of the news feed in your
bookmarks. This way you can keep details of new content within your web browser and stay up to
date without even visiting the web site.

The good news is that adding a news feed to your own web site is quite straightforward. For
example we created the news feed are used to help web browsers and other software
automatically discover the news feed when the web site is visited. However, most of the news
feeds published by our clients are created automatically as a to manage their news distribution.
Blogger automatically creates its news feed in Atom format.

The format of the news feed published by a third party service doesn’t really make much
difference though. Atom formatted news feeds were originally developed to address technical
issues which existed with the emerging standards for RSS news feeds. They also contain many
features that aren’t available in RSS 2.0 and as such are sometimes considered a superior format.
However the RSS format is easier to implement and more widely recognised. RSS is also used as
a general way to describe all types of news feed and is taken as the abbrevitation of Really Simple
Syndication, Rich Site Summary or RDF Site Summary depending on who you talk to.

RSS
RSS stands for both Rich Site Summary and Really Simple Syndication but it always refers to the
same technology.

It is a mean of transmitting and updating news in an automated way.

Most news sites (including virtually all blogs) will publish what is called an RSS feed which is
regularly updated with the latest available headlines and/or articles.

The RSS feed is not human readable. It is an format which is designed to be read by machines
rather than humans.

[Department of CSE] 71
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Reading RSS

To take advantage of an RSS feed you would use a piece of software called an RSS aggregator.
Most of them are very similar to email client programs, but instead of incoming emails, they
display news from various sources (from all the feeds you have registered with, or "subscribed to"
as is commonly said but it has nothing to do with money). Unread news typically appear in bold,
just as unread emails do.

An RSS aggregator makes it very convenient to follow up on news from a large number of
sources in a single place is an example of an RSS Reader.

Just like there is webmail, there are also are web-RSS-aggregators. it is such an online aggregator.
Il allows you to track all your news from a single place you can access with a regular web
browser.

Also, most modern web browsers will also handle RSS feeds, but in a limited manner. They will
use an RSS feed as a dynamic bookmark folder with automatic bookmarks to all the news in the
feed. Unlike aggregators, browsers will not save the news if you don't check on them every day.

Finally, on a more professional level, some websites will aggregate news from different sources
onto a single site. Hence the "syndication" in the name.

Producing RSS

While you could theoretically write an RSS file by hand and update it regularly, writing XML
manually is a tedious task.

Most RSS feeds are produced automatically by the same content management software which
also generates the web pages dynamically. All blog tools for example can generate RSS feeds on
the fly. is an example of such a blog tool.

Distributing RSS

Whether you generate your RSS by hand or have a tool generate it automatically, you need to
make it available on the web for users (and their "client" software) to consume.

Different flavours

There are different versions of RSS in use. RSS 2.0 is the most common. It is used for news/blog
feeds as well as for Podcasting.

A newer format, called Atom, is a more standardized way of providing XML content updates.
However, it has not gotten wide acceptance yet outside of the blog communities. (Again, almost
all blog tools can generate an Atom feed on the fly.)

[Department of CSE] 72
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

RSS 2.0

RSS 2.0 has the widest acceptance of any feed format. Much of that has to do with the defacto use
of it by WordPress, but it is also the one variety of RSS format that seems to have solved some of
the problems presented by earlier versions. Of the two feed types, RSS is most widley used but
also has signifigant downfalls.
For one, RSS does not allow any well-formed XML markup in it’s content. This is very bad when
it comes to using RSS-syndicated content elsewhere. In fact, it only supports plain text or escaped
HTML which, without getting into the technical issues surrounding that, simply means it’s very
difficult to work with.
RSS has only three required fields on a per item basis- title, link and description. There are a
variety of optional fields but some key features, such as a “last updated” field are missing.

Atom 1.0

Atom is a relatively recent spec and is much more robust and feature-rich than RSS. For instance,
where RSS requires descriptive fields such as title and link only in item breakdowns, Atom
requires these things for both items and the full feed.

Atom feeds provide an “updated” field which means that any feeds that are modified have a
timestamp associated with them. Trust me when I say I find this useful.

A cool feature of Atom has to do with autodiscovery. Most of the time, if you point your browser
to a feed-enabled website, autodiscovery kicks in and the browser alerts you in its own unique
way to the presence of a feed. The same thing happens when you point a feed reader to a feed-
enabled website as opposed to the specific feed itself. While feed autodiscovery has been around
for a long time, Atom feeds actually contain a self pointer autodiscovery URL which is highly
unique from RSS itself.

There’s quite a lot different in terms of the two specs. If you’re really interested in discovering the
technical differences between the two, I encourage you to read . He really nails it very well.
RSS vs Atom . which one is better ?

RSS is a family of formats used to publish frequently updated works—such as blog entries, news
headlines, audio, and video—in a standardized format.

[Department of CSE] 73
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

An RSS document which is called a “feed”, “web feed” ,or “channel” includes full or summarized
text, plus metadata such as publishing dates andauthorship.RSS feeds benefit publishers by letting
them syndicate content automatically

RSS Example
<?xml version=”1.0″ encoding=”UTF-8″ ?>
<rss version=”2.0″>
<channel>
<title>RSS Title</title>
<description>This is an example of an RSS feed</description>
<link>http://www.someexamplerssdomain.com/main.html</link&gt;
<lastBuildDate>Mon, 06 Sep 2010 00:01:00 +0000 </lastBuildDate>
<pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>
<ttl>1800</ttl>
<item>
<title>Example entry</title>
<description>Here is some text containing an interesting description.</description>
<link>http://www.wikipedia.org/</link&gt;
<guid>unique string per item</guid>
<pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>
</item>
</channel>
</rss>

Atom
The advent of the ATOM syndication standard was a response to the design flaws of the
RSS standard. The primary advantage of the ATOM is its adaptation as the IETF standard.

The Atom Syndication Format is an XML language used for web feeds, while the Atom
Publishing Protocol (AtomPub or APP) is a simple HTTP-based protocol for creating and
updating web resources.ATOM code has been built from the ground with modularity in mind.
Therefore, a great majority of its code is reusable even with other XML vocabularies like RSS

Example of an Atom 1.0 feed


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

<feed xmlns="http://www.w3.org/2005/Atom">

<title>Example Feed</title>

<subtitle>A subtitle.</subtitle>

<link href="http://example.org/feed/" rel="self" />

[Department of CSE] 74
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

<link href="http://example.org/" />

<id>urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6</id>

<updated>2003-12-13T18:30:02Z</updated>

<entry>

<title>Atom-Powered Robots Run Amok</title>

<link href="http://example.org/2003/12/13/atom03" />

<link rel="alternate" type="text/html"


href="http://example.org/2003/12/13/atom03.html"/>

<link rel="edit" href="http://example.org/2003/12/13/atom03/edit"/>

<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>

<updated>2003-12-13T18:30:02Z</updated>

<summary>Some text.</summary>

<author>

<name>John Doe</name>

<email>[email protected]</email>

</author>

</entry></feed>

Comparison of RSS with Atom


Both RSS and Atom are widely supported in all major consumer feed readers. However,
Atom has several advantages over RSS, such as less restrictive licensing, IANA registered MIME
type, an XMLnamespace, support for relative URIs, and RelaxNG support. Technically, Atom
should be considered the more advanced syndication format between the two
The following table summarizes those RSS elements that have their equivalents in Atom.

[Department of CSE] 75
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

RSS 2.0 Atom 1.0


author Author

category Category

channel Feed

copyright Rights

description Subtitle

description summary and/or content

generator Generator

guid Id

image Logo

item entry

lastBuildDate (in channel) updated

Link link

managingEditor author or contributor

pubDate published (subelement of entry)

Title title

Ttl –

Summary of RSS vs Atom:


1.ATOM code is modular and reusable while RSS code is not & ATOM is an IETF standard
while RSS is not
2.RSS still holds dominance in the syndication format due to its head start and popularity.

[Department of CSE] 76

You might also like