0% found this document useful (0 votes)
69 views17 pages

Unit-5 Web Technology

The document provides an overview of XML, its syntax, and its usage in web services. It explains XML's structure, including elements, attributes, and Document Type Definitions (DTD), as well as XML Schema for validation. Additionally, it covers XSL and XSLT for transforming XML documents into other formats like HTML.
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)
69 views17 pages

Unit-5 Web Technology

The document provides an overview of XML, its syntax, and its usage in web services. It explains XML's structure, including elements, attributes, and Document Type Definitions (DTD), as well as XML Schema for validation. Additionally, it covers XSL and XSLT for transforming XML documents into other formats like HTML.
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/ 17

Page |1

Unit-5
XML, AJAX, and Web Services
Introduction to XML

The Extensible Markup Language (XML) is a general-purpose markup language. An Extensible Mark Up file
is defined as a text-based language that carries data in the form of tags not the format of the data. It is
classified as an extensible language because it allows its users to define their own tags. Its primary purpose
is to facilitate the sharing of structured data across different information systems, particularly via the
Internet.

It is comparable with other text-based serialization languages such as JSON. XML is recommended by the
World Wide Web Consortium.

Why use XML?

• Web services such as SOAP and REST use XML format to exchange information. Learning what
XML is and how it works will get you competitive advantage as a developer since modern
applications make heavy use of web services.
• XML documents can be used to store configuration settings of an application
• It allows you to create your own custom tags which make it more flexible.

XML Syntax Rules

You must follow these rules when you create XML syntax:

• All XML elements must have a closing tag.


• XML tags are case sensitive.
• All XML elements must be properly nested.
• All XML documents must have a root element.
• Attribute values must always be quoted.

Syntax:

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


<root>
<child>
<subchild>......</subchild>
</child>
</root>

The first line <?xml version="1.0" encoding="UTF-8"?> is called XML Prolog. It is optional, however when
we include it in the XML document, it should always be the first line of the document. XML Prolog defines
the XML version and the encoding used in the XML document.

Jhalnath Chapagain | GM COLLEGE


Page |2

Examples:

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


<book>
<name>A Song of Ice and Fire</name>
<author>George R. R. Martin</author>
<language>English</language>
<genre>Epic fantasy</genre>
</book>
The tag <book> is the root of this XML document. An XML document should always have a root
element and at the end of the document this root element needs a closing tag, just like </book>
that we have used in the above example.

The tags <name>, <author>, <language> and <genre> are the child elements of the root element
<book>.
Another Example:
<students>
<student>
<name>Ram</name>
<age>35</age>
<subject>Maths</subject>
<gender>Male</gender>
</student>
<student>
<name>Hari </name>
<age>33</age>
<subject>Science</subject>
<gender>Male</gender>
</student>
<student>
<name>Sita</name>
<age>36</age>
<subject>Arts</subject>
<gender>Female</gender>
</student>
</students>

Jhalnath Chapagain | GM COLLEGE


Page |3

XML DTD
A Document Type Definition (DTD) is a document that describes the structure of an XML
document, what elements and attributes it contains and what values they may have. DTD are
defined in the Document with the declaration <!DOCTYPE > and each XML document holds one
DTD.
A DTD can be declared inline in your XML document, or as an external reference.

Internal DTD
This type of DTD is declared inside the XML Document. This is an XML document with a Document
Type Definition:
<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Ram</to>
<from>Shyam</from>
<heading>Reminder</heading>
<body>Don't forget our meeting this
weekend</body>
</note>

In the above example, the DTD is interpreted like this:


!ELEMENT note (defines the element "note" as having four elements: "to,from,heading,body".)
!ELEMENT to (defines the "to" element to be of the type "PCDATA".)
!ELEMENT from ( defines the "from" element to be of the type "PCDATA")
and so on.....

Jhalnath Chapagain | GM COLLEGE


Page |4

There are 2 data types, PCDATA and CDATA

• PCDATA is parsed character data.


• CDATA is character data, not usually parsed.

External DTD
DTDs can also be declared in an external file at the beginning of the XML document. Similar to internal
declarations, they must be wrapped in the <!DOCTYPE> definition. An example of an external DTD
declaration is as follows:

employee.xml

<?xml version="1.0"?>

<!DOCTYPE employee SYSTEM "employee.dtd">

<employee>

<firstname>Ram</firstname>

<lastname>Karki</lastname>

<email>[email protected]</email>

</employee>

employee.dtd

<!ELEMENT employee (firstname,lastname,email)>

<!ELEMENT firstname (#PCDATA)>

<!ELEMENT lastname (#PCDATA)>

<!ELEMENT email (#PCDATA)>

The building blocks of XML documents

XML documents (and HTML documents) are made up by the following building blocks:

• Elements
• Tags
• Attributes
• Entities
• #PCDATA
• CDATA

Jhalnath Chapagain | GM COLLEGE


Page |5

Elements

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

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

Empty elements

Empty elements are declared with the keyword EMPTY inside the parentheses:

<!ELEMENT element-name (EMPTY)>

example:

<!ELEMENT img (EMPTY)>

Elements with data

Elements with data are declared with the data type inside parentheses:
<!ELEMENT element-name (#PCDATA)>
or
<!ELEMENT element-name (ANY)>
example:
<!ELEMENT note (#PCDATA)>

Tags

Tags are used to markup elements. A starting tag like <element_name> mark up the beginning of an
element, and an ending tag like </element_name> mark up the end of an element.

Examples:
A message element: <message>some message in between</message>

Attributes

Attributes provide extra information about elements. Attributes are placed inside the start tag of an
element. Attributes come in name/value pairs.

Entities

Entities as variables are used to define common text. Entities are expanded when a document is parsed
by an XML parser.

Jhalnath Chapagain | GM COLLEGE


Page |6

The following entities are predefined in XML:

Entity References Character

&lt; <
&gt; >
&amp; &
&quot; "
&apos; '

Declaring Attributes

In the DTD, XML element attributes are declared with an ATTLIST declaration. An attribute declaration
has the following syntax:

<!ATTLIST element-name attribute-name attribute-type default-value>

As you can see from the syntax above, the ATTLIST declaration defines the element which can have the
attribute, the name of the attribute, the type of the attribute, and the default attribute value.

Attribute declaration example

DTD example:

<!ELEMENT square (EMPTY)>

<!ATTLIST square width CDATA "0">

XML example:

<square width="100"></square>

#PCDATA

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

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

CDATA

CDATA also means character data. CDATA is text that will NOT be parsed by a parser. Tags inside the text
will NOT be treated as markup and entities will not be expanded. Let's take an example for CDATA:

<?xml version="1.0"?>
<!DOCTYPE employee SYSTEM "employee.dtd">
<employee>

Jhalnath Chapagain | GM COLLEGE


Page |7

<![CDATA[
<firstname>Raju</firstname>
<lastname>Rai</lastname>
<email>[email protected]</email>
]]>
</employee>

In the above CDATA example, CDATA is used just after the element employee to make the data/text
unparsed, so it will give the value of employee:

<firstname>Raju</firstname><lastname>Rai</lastname><email>[email protected]</email>

XML document with an internal DTD:

<?xml version="1.0"?>

<!DOCTYPE address [

<!ELEMENT address (name, email, phone, birthday)>

<!ELEMENT name (first, last)>

<!ELEMENT first (#PCDATA)>

<!ELEMENT last (#PCDATA)>

<!ELEMENT email (#PCDATA)>

<!ELEMENT phone (#PCDATA)>

<!ELEMENT birthday (year, month, day)>

<!ELEMENT year (#PCDATA)>

<!ELEMENT month (#PCDATA)>

<!ELEMENT day (#PCDATA)>

]>

<address>

<name>

<first>Rohit</first>

<last>Sharma</last>

</name>

<email>[email protected]</email>

<phone>9876543210</phone>

Jhalnath Chapagain | GM COLLEGE


Page |8

<birthday>

<year>1987</year>

<month>June</month>

<day>23</day>

</birthday>

</address>

XML document with an external DTD:

stock.dtd

<?xml version="1.0"?>

<!ELEMENT Broker (sname,branch,contact)>

<!ELEMENT bname (#PCDATA)>

<!ELEMENT branch (#PCDATA)>

<!ELEMENT contact (#PCDATA)>

vision.xml

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

<!DOCTYPE Broker SYSTEM "stock.dtd">

<Broker>

<bname>Secured Securities</bname>

<branch>nine</branch>

<contact>9819023656</contact>

</Broker>

Jhalnath Chapagain | GM COLLEGE


Page |9

XML Schema
XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe and validate the
structure and the content of XML data. XML schema defines the elements, attributes and data types.
Schema element supports Namespaces. It is similar to a database schema that describes the data in a
database.

An XML document is called "well-formed" if it contains the correct syntax. A well-formed and valid XML
document is one which have been validated against Schema.

XML Schema Example

contact.xml

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


<contact xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="contact.xsd">
<name>Binod Choudhary</name>
<company>CG CORP GLOBAL</company>
<phone>9819045603</phone>
</contact>
The line above: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" tells the XML parser that
this document should be validated against a schema.

The line: xsi:schemaLocation="contact.xsd" specifies WHERE the schema resides (here it is in the same
folder as "contact.xml").

contact.xsd

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


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

Elements

An element can be defined within an XSD as follows −

Jhalnath Chapagain | GM COLLEGE


P a g e | 10

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

Definition Types
We can define XML schema elements in the following ways −

a. Simple Type
Simple type element is used only in the context of the text. Some of the predefined simple types are:
xs:int, xs:boolean, xs:string, xs:date. For example −
Example:
<xs:element name = "phone_number" type = "xs:int" />

b. Complex Type
A complex type is a container for other element definitions. This allows you to specify which child
elements an element can contain and to provide some structure within your XML documents. For
example –
<xs:element name = "Address">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>

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

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

<xs:element name="Order"> <Order OrderID="6" />


<xs:complexType>
<xs:attribute name="OrderID" type="xs:int" use="optional"/> - or no attribute –
</xs:complexType>
</xs:element> <Order />

Jhalnath Chapagain | GM COLLEGE


P a g e | 11

XSL and XSLT


XSL (eXtensible Stylesheet Language) is a styling language for XML. XSLT stands for XSL Transformations.
XML does not use predefined tags, and therefore the meaning of each tag is not well understood.
A <table> element could indicate an HTML table, a piece of furniture, or something else - and browsers
do not know how to display it!
So, XSL describes how the XML elements should be displayed.
XSLT stands for XSL Transformations. XSLT is used to transform an XML document into another XML
document, or another type of document that is recognized by a browser, like HTML and XHTML.
Normally XSLT does this by transforming each XML element into an (X)HTML element.

With XSLT you can add/remove elements and attributes to or from the output file. You can also
rearrange and sort elements, perform tests and make decisions about which elements to hide and
display, and a lot more.

cdcatlog.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
.
.
</catalog>

cdcatalog.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>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">

Jhalnath Chapagain | GM COLLEGE


P a g e | 12

<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

XML processing with PHP


To read and update, create and manipulate an XML document, you will need an XML parser. SimpleXML
is a PHP extension that allows us to easily manipulate and get XML data.SimpleXML is a tree-based
parser. SimpleXML provides an easy way of getting an element's name, attributes and textual content if
you know the XML document's structure or layout. SimpleXML turns an XML document into a data
structure you can iterate through like a collection of arrays and objects.

PHP SimpleXML - Read From File


The PHP simplexml_load_file() function is used to read XML data from a php file.
Employees.xml
<?xml version="1.0" encoding="utf-8"?>

<employees status = "ok">

<record man_no = "101">

<name>Joe Paul</name>

<position>CEO</position>

</record>

<record man_no = "102">

<name>Tasha Smith</name>

<position>Finance Manager</position>

</record>

</employees>

Jhalnath Chapagain | GM COLLEGE


P a g e | 13

Index.php
<?php

$xml = simplexml_load_file('Employees.xml');

echo '<h2>Employees Listing</h2>';

$list = $xml->record;

for ($i = 0; $i < count($list); $i++) {

echo '<b>Man no:</b> ' . $list[$i]->attributes()->man_no . '<br>';

echo 'Name: ' . $list[$i]->name . '<br>';

echo 'Position: ' . $list[$i]->position . '<br><br>';

}
?>
(Note:Run this file from local server to demonstrate xml processing through php)

Asynchronous JavaScript and XML (AJAX)

Ajax is an acronym for Asynchronous Javascript and XML. It is used to communicate with the server
without refreshing the web page and thus increasing the user experience and better performance.

There are two types of requests synchronous as well as asynchronous. Synchronous requests are the one
which follows sequentially i.e if one process is going on and in the same time another process wants to be
executed, it will not be allowed that means the only one process at a time will be executed. This is not
good because in this type most of the time CPU remains idle such as during I/O operation in the process
which are the order of magnitude slower than the CPU processing the instructions. Thus to make the full
utilization of the CPU and other resources use asynchronous calls. Why the word javascript is present
here. Actually, the requests are made through the use of javascript functions. Now the term XML which is
used to create XMLHttpRequest object.

Jhalnath Chapagain | GM COLLEGE


P a g e | 14

Thus the summary of the above explanation is that Ajax allows web pages to be updated asynchronously
by exchanging small amounts of data with the server behind the scenes.

For implementing Ajax, only be aware of XMLHttpRequest object. It is an object used to exchange data
with the server behind the scenes. Try to remember the paradigm of OOP which says that object
communicates through calling methods (or in general sense message passing). The same case applied
here as well. Usually, create this object and use it to call the methods which result in effective
communication. All modern browsers support the XMLHttpRequest object.

Basic Syntax: The syntax of creating the object is given below

req = new XMLHttpRequest();

There are two types of methods open() and send(). Uses of these methods explained below.

req.open("GET", "abc.php?x=25", true);


req.send();

The above two lines described the two methods. req stands for the request, it is basically a reference
variable. The GET parameter is as usual one of two types of methods to send the request. Use POST as
well depending upon whether send the data through POST or GET method. The second parameter being
the name of the file which actually handles the requests and processes them.

The specified query is in the form of URL followed by ? which is further followed by the name of the
variable then = and then the corresponding value.

If sending two or more variables use ampersand(&) sign between the two variables.

The third parameter is true, it tells that whether the requests are processed asynchronously or
synchronously. It is by default true which means that requests are asynchronous. The open() method
prepares the request before sending it to the server.

The send method is used to send the request to the server.

The above method as shown applies for GET request. Sending the data through the POST, then send it in
the send method as shown below.

req.send("name=johndoe&marks=99");

Jhalnath Chapagain | GM COLLEGE


P a g e | 15

Properties of XMLHttpRequest object


The common properties of XMLHttpRequest object are as follows:

Property Description

onReadyStateChange It is called whenever readystate attribute changes. It must not be used with synchronous
requests.

readyState represents the state of the request. It ranges from 0 to 4.


0 UNOPENED open() is not called.
1 OPENED open is called but send() is not called.
2 HEADERS_RECEIVED send() is called, and headers and status are available.
3 LOADING Downloading data; responseText holds the data.
4 DONE The operation is completed fully.

reponseText returns response as text.

responseXML returns response as XML

Methods of XMLHttpRequest object


The important methods of XMLHttpRequest object are as follows:

Method Description

void open(method, URL) opens the request specifying get or post method
and url.

void open(method, URL, async) same as above but specifies asynchronous or not.

void open(method, URL, async, username, same as above but specifies username and
password) password.

void send() sends get request.

void send(string) send post request.

setRequestHeader(header,value) it adds request headers.

Jhalnath Chapagain | GM COLLEGE


P a g e | 16

AJAX Example
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>

ajax_info.txt

Jhalnath Chapagain | GM COLLEGE


P a g e | 17

Web services
A web service is any piece of software that makes itself available over the internet and
uses a standardized XML messaging system. XML is used to encode all communications
to a web service. For example, a client invokes a web service by sending an XML message,
then waits for a corresponding XML response.

To summarize, a complete web service is, any service that −

• Is available over the Internet or private (intranet) networks


• Uses a standardized XML messaging system
• Is not tied to any one operating system or programming language
• Is self-describing via a common XML grammar
• Is discoverable via a simple find mechanism

Components of Web Service


XML and HTTP is the most fundamental web services platform. The following components are used by all
typical web services:

SOAP (Simple Object Access Protocol)

SOAP stands for “Simple Object Access Protocol.” It is a transport-independent messaging protocol. SOAP
is built on sending XML data in the form of SOAP Messages. A document known as an XML document is
attached to each message. Only the structure of the XML document, not the content, follows a pattern.
The best thing about Web services and SOAP is that everything is sent through HTTP, the standard web
protocol.

WSDL ( Web Service Description Language )


WSDL ( Web Service Description Language ) is how the Web service is described to the outside world. It
defines an XML grammar for describing services and serves as a recipe for automating the details in
application communication. WSDL describes a service’s methods, data inputs/outputs, and contact
mechanism.

UDDI(Universal Description, Discovery, and Integration)


UDDI( Universal Description, Discovery, and Integration ) provides a mechanism for Web services
providers to publish new and updated Web services and a mechanism for service consumer to find and
access published Web services. UDDI enables businesses to publish and advertise the services they offer
and describe how these services should be used.

Jhalnath Chapagain | GM COLLEGE

You might also like