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

Unit-3 The Client Tier

This document provides an overview of XML (Extensible Markup Language), highlighting its characteristics, uses, and structure. It explains the importance of XML in data storage and sharing, the syntax for creating XML documents, and the rules for defining XML elements and attributes. Additionally, it covers XML namespaces to avoid naming conflicts and includes examples to illustrate the concepts discussed.

Uploaded by

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

Unit-3 The Client Tier

This document provides an overview of XML (Extensible Markup Language), highlighting its characteristics, uses, and structure. It explains the importance of XML in data storage and sharing, the syntax for creating XML documents, and the rules for defining XML elements and attributes. Additionally, it covers XML namespaces to avoid naming conflicts and includes examples to illustrate the concepts discussed.

Uploaded by

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

Unit-3: The Client tie

====================================================================

Syllabus:

====================================================================

Introduction to XML
XML (Extensible Markup Language) is a markup language similar to HTML, but without
predefined tags to use. Instead, you define your own tags designed specifically for your needs.
This is a powerful way to store data in a format that can be stored, searched, and shared. Most
importantly, since the fundamental format of XML is standardized, if you share or transmit XML
across systems or platforms, either locally or over the internet, the recipient can still parse the
data due to the standardized XML syntax.

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

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

 XML is extensible − XML allows you to create your own self-descriptive tags, or
language, that suits your application.
 XML carries the data, does not present it − XML allows you to store the data
irrespective of how it will be presented.
 XML is a public standard − XML was developed by an organization called the World
Wide Web Consortium (W3C) and is available as an open standard.

By Lec. Teksan Gharti Page 1


Use of XML
XML is one of the most widely-used formats for sharing structured information between
programs, between people, between computers and people, both locally and across networks.

Hence…

 It can work behind the scene to simplify the creation of HTML documents for large web
sites.
 It can be used to exchange the information between organizations and systems.
 It can be used for offloading and reloading of databases.
 It can be used to store and arrange the data, which can customize your data handling
needs.
 It can easily be merged with style sheets to create almost any desired output.
 Virtually, any type of data can be expressed as an XML document.

Structure of an XML document

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


<message>
<to>Students</to>
<from>Teacher</from>
<subject>Regarding assignment submission</subject>
<text>All students will have to submit assignment by tomorrow.</text>
</message>

Below is the explanation of each point.

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


 This line is called XML Prolog or XML declaration.
 This line is optional i.e, it can be either used or not in an XML document. However, it
should be the very first line if used.
 The version=”1.0″ is the version of the XML currently used.
 The encoding=” UTF-8″ specifies the character encoding used while writing an XML
document, for example, êèé is for French and so on. Its default value is “UTF-8”.
 This declaration is case sensitive for example “xml” should must be in lower case .

<message>
By Lec. Teksan Gharti Page 2
 This is the root element and all the remaining elements <to>, <from> etc are the child
element and they reside within the root element.
 Every XML file should have one or more Root elements to avoid error and It is case
sensitive.
<to>, <from>, <subject>, <text>

 These elements are the child element and they reside within the root element <message>.

XML Elements and Attributes


XML Elements
The XML elements are the basic building block of the XML document. It is used as a
container to store text elements, attributes, media objects etc. Every XML documents contain at
least one element whose scopes are delimited by start and end tags or in case of empty elements
it is delimited by an empty tag.

Syntax:
<element-name attributes> Contents...</element-name>

 element-name: It is the name of element.


 attributes: The attributes are used to define the XML element property and these
attributes are separated by white space. It associates the name with a value, which
is a string of characters.
Example:
<?xml version = “1.0”?>
<contactinfo>
<address category = “collage”>
<name>Teksan</name>
<College>Nccs</College>
<mobile>123454567890</mobile>
</address>
</contactinfo>

Above is the example of an XML document describing the address of a college student using
XML elements.

Rules to define XML elements:

By Lec. Teksan Gharti Page 3


 An element can contain alphanumeric values or characters. But only three special
characters are required in the names these are hyphen, underscore and period.
 Names are case sensitive. It means lower case letters have different meaning and upper
case characters have different meaning. For example address, Address, aDDress are
different names.
 Both start and end tags for elements need to be same.
 An element, which is a container, can contain text or elements

XML attribute
The XML attribute is a part of an XML element. The addition of attribute in XML element
gives more precise properties of the element i.e, it enhances the properties of the XML element.
Syntax:
<element_name attribute1 attribute2 ... > Contents... </element_name>

In the above syntax element_name is the name of an element which can be any name.
The attribute1, attribute2, … is XML attribute having unique attribute name. Then in the content
section, any message can be written and at the end, the element name is ended.

Example:

<address category = “collage”>

In the above example, XML element is address, the category is the attribute name
and collage are the attribute value, Attribute name and its value always appear in pair. The
attribute name is used without any quotation but attribute value is used in single (‘’) or double
quotation (“”).

Syntax Rules for creating XML document

1. Root Element is mandatory in XML


XML document must have a root element. A root element can have child elements and sub-
child elements.
Example:
<?xml version="1.0" encoding="UTF-8"?>
<message>
<to>Steve</to>
<from>Paul</from>
<subject>Message from teacher to Student</subject>
<text>You have an exam tomorrow at 9:00 AM</text>
</message>

In The above XML document, <message> is the root element and <to>, <from>,
By Lec. Teksan Gharti Page 4
<subject> and <text> are child elements.

2. XML is case sensitive


XML is a case sensitive language.

For example:
This is valid :<from>Paul</from>
This is invalid: <from>Paul</From>

3. XML Prolog
<?xml version="1.0" encoding="UTF-8"?>
This line is called the XML Prolog. It is an optional line, however it should be the first
line when you mention it. It specifies the XML version and the encoding used in the XML
document.

4. Elements should not overlap


All the elements in XML should be properly nested and they should not overlap.

<class><teacher>Rick</class></teacher> -->Wrong (Not nested properly)


<class><teacher>Rick</teacher></class> -->Correct (Correctly nested)

5. Attributes in XML
An opening tag in XML can have attributes, these attributes are name & value pairs.
Attribute names are case sensitive and should not be in quotation marks. Attribute values
should be in single or double quotation.

<text category = "message">You have an exam tomorrow at 9:00 AM</text>


Here category is the attribute name and message is the attribute value.

6. XML elements must have a closing tag


All XML documents must have a closing tag.

<text category = message>hello</text> -->correct


<text category = message>hello -->wrong

7. Comments in XML

By Lec. Teksan Gharti Page 5


This is how a comment should look like in XML document.
<!-- This is just a comment -->

8. White-spaces are preserved in XML


Unlike HTML that doesn’t preserve white space, the XML document preserves white
spaces.

XML Tree(not in syllabus)


XML tree structure is also called as tree model or hierarchical model. An XML document
has a self-descriptive structure. The tree structure is often referred to as XML Tree and plays an
important role to describe any XML document easily.

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

Syntax

The basic Syntax structure is drawn below:

By Lec. Teksan Gharti Page 6


How to design a tree in XML?
At first, we shall see an XML document, and based on this; we can design a tree
structure as the tree structure is the best supportive of XML language, which has the capability of
deriving positions, powerfully combining hierarchical formats. We have some rules for
designing a structure and a relationship between the two elements in XML Document. The rules
are stated as follows:
 Rule 1 – Descendants: If the XML element ‘X’ is contained by another element ‘Y’,
then X is Y’s descendant.
 Rule 2 – Ancestors: If the XML element ‘X’ has element ‘Y’, then Y is the ancestors of
X.
 Rule 3 – The name of the label in the section data should be relative.

Examples of XML Document


<?xml version="1.0" encoding="UTF-8"?>
<employee>
<emp_info id="1">
<name>
<first_name>Teksan</first_name>
<middle_name>Gharti</middle_name>
<last_name>magar</last_name>
</name>
<contact_info>
<company_info>
<comp_name>Capgemini</comp_name>
<comp_location>
<street>Tower-1, Infocity</street>
<city>mumbai</city>
<phone>000-478-1414</phone>
</comp_location>
<designation>Software Developer</designation>
</company_info>
<phone>000-987-4745</phone>
<email>[email protected]</email>
</contact_info>
</emp_info>
</employee>

In this example, the first line states version of the XML document as “1.0”. So, here <employee>
is the root element followed by many child elements.

By Lec. Teksan Gharti Page 7


XML Tree

The Tree structure for the above xml document is shown below:

XML Namespace
In XML, elements name is defined by the developer so there is a chance to conflict in
name of the elements. To avoid these types of conflictions we use XML Namespaces. We can
say that XML Namespaces provide a method to avoid element name conflict. Generally, this
conflict occurs when we try to mix XML documents from different XML application.

So,
An XML namespace is a collection of names that can be used as element or attribute
names in an XML document. The namespace qualifies element names uniquely on the Web in
order to avoid conflicts between elements with the same name. The namespace is identified by
some Uniform Resource Identifier (URI), either a Uniform Resource Locator (URL), or a
Uniform Resource Name (URN), but it doesn't matter what, if anything, it points to. URIs are
used simply because they are globally unique across the Internet.

By Lec. Teksan Gharti Page 8


Namespace Declaration
Declaration of the namespace in the XML document is very important which are done by
making use of a family of reserved attributes. And these attributes can be put on the way directly
or default in the following syntax:

Syntax
<element xmlns:name = "URL">
Here,
 The Namespace starts with the keyword xmlns.
 The word name is the Namespace prefix.
 The URL is the Namespace identifier.

Example1
Following is a simple example of XML Namespace …

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


<cont:contact xmlns:cont = "www.xyz.com/profile">
<cont:name>Teksan </cont:name>
<cont:company>Reliance</cont:company>
<cont:phone>(011) 123-4567</cont:phone>
</cont:contact>

Here, the Namespace prefix is cont, and the Namespace identifier (URI)
as www.xyz.com/profile. This means, the element names and attribute names with the cont
prefix (including the contact element), all belong to the www.xyz.com/profile namespace.

Let's take an example with two tables:

Table1:
<table>
<tr>
<td>Apple</td>
<td>Banana</td>
</tr>
</table>

Table2:
By Lec. Teksan Gharti Page 9
This table carries information about a computer table.
<table>
<name>Computer table</name>
<width>80</width>
<length>120</length>
</table>

If you add these both XML fragments together, there would be a name conflict because
both have <table> element. Although they have different name and meaning.

Hence to get rid of name conflict we use XML namespace.

1) By Using a Prefix
Name conflicts in XML can easily be avoided using a name prefix.

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

<f:table>
<f:name> Computer table </f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>

In the example above, there will be no conflict because the two <table> elements have
different names.

2) By Using xmlns Attribute


You can use xmlns attribute to define namespace with the following syntax:

<element xmlns:name = "URL">

Example

By Lec. Teksan Gharti Page 10


<root>
<h:table xmlns:h="http://www.abc.com/TR/html4/">
<h:tr>
<h:td>Apple</h:td>
<h:td>Banana</h:td>
</h:tr>
</h:table>

<f:table xmlns:f="http://www.xyz.com/furniture">
<f:name>Computer table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>

In the above example, the <table> element defines a namespace and when a namespace is
defined for an element, the child elements with the same prefixes are associated with the same
namespace.

Example

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


<purchaseOrder xmlns="http://www.somecompany.com/order/PO>
<firstname>Fred</firstname>
<surname>Bloggs</surname>
<address xmlns="http://www.somecomapany.com/order/ADDR">
<addressLine1>2 South Road</address1>
<addressLine2/>
<town>Colchester</town>
<county>Essex</county>
<postcode>CO8 9SR</postcode>
</address>
<telephone>01334 234567</telephone>
</purchaseOrder>

The above example the first namespaces is defined within the purchaseOrder element and
the other is defined within the address element. The final part of the URI (/PO and /ADDR in the
example) completes the URL to create a unique identifier for each namespace. All elements
descending the purchaseOrder element will inherit the namespace. This also applies to all
elements descending address element.
By Lec. Teksan Gharti Page 11
Namespaces can be declared either explicitly or by default. With an explicit
declaration, you define a shorthand, or prefix, to substitute for the full name of the namespace.
You use this prefix to qualify elements belonging to that namespace. A default declaration
declares a namespace to be used for all elements within its scope, and a prefix is not used.

The Default Namespace


The default namespace is used in the XML document to save you from using prefixes in all
the child elements.

The only difference between default namespace and a simple namespace is that: There is
no need to use a prefix in default namespace.

You can also use multiple namespaces within the same document just define a namespace
against a child node.

Example of Default Namespace:


<webnotes xmlns="http://www.xyz.com/web-notes">
<notes>
<title>web-study notes</title>
<author>xyz</author>
</ notes>
...
</ webnotes >

Using default namespaces can be complicated when many are declared within the
XML tree. It is recommended to use prefixed namespaces. A qualified name assigns a prefix to
an element that maps to a declared namespace.

It is not required to qualify all elements within the XML. You can rely on default
namespace to determine the namespace for all elements not explicitly prefixed. This is shown in
the example below:

Example:
<?xml version="1.0" encoding="UTF-8" ?>
<purchaseOrder xmlns="http://www.somecompany.com/order/PO
By Lec. Teksan Gharti Page 12
xmlns:addr="http://www.somecomapany.com/order/ADDR>
<firstname>Fred</firstname>
<surname>Bloggs</surname>
<addr:address">
<addr:addressLine1>2 South Road</addr:address1>
<addr:addressLine2/>
<addr:town>Colchester</addr:town>
<addr:county>Essex</addr:county>
<addr:postcode>CO8 9SR</addr:postcode>
</addr:address>
<telephone>01334 234567</po:telephone>
</purchaseOrder>

In the example above, the namespace declaration is moved to the purchaseOrder


element. This is optional and can be declared within the address element. Adding the namespace
gives the address namespace scope throughout the whole of the document and is not restricted to
the address element.

Namespaces declared explicitly


An element using a prefix is defined with two parts, a prefix and a local name separated
with a “:” e.g addr:address. All descendants of the address element should also be prefixed as
shown in the example below:

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


<po xmlns:po="http://www.somecompany.com/order/PO
xmlns:addr="http://www.somecomapany.com/order/ADDR>
<po:firstname>Fred</po:firstname>
<po:surname>Bloggs</po:surname>
<addr:address">
<addr:addressLine1>2 South Road</addr:address1>
<addr:addressLine2/>
<addr:town>Colchester</addr:town>
<addr:county>Essex</addr:county>
<addr:postcode>CO8 9SR</addr:postcode>
</addr:address>
<po:telephone>01334 234567</po:telephone>
</po:purchaseOrder>
XML schema

By Lec. Teksan Gharti Page 13


An XML schema is the structural layout of an XML document, expressed in terms of
constraints and contents of the document. Constraints are expressed using a combination of the
following:
 Grammatical rules governing the order of elements
 Data types governing an element and content attribute
 Boolean predicates that the content has to satisfy
 Specialized rules including uniqueness and referential integrity constraints

XML Schema Definition (XSD)


An XML schema, commonly known as an XML Schema Definition (XSD), is the current
standard schema language for all XML documents and data. It is used to describe and validate
the structure and the content of XML data. It is a framework document that defines the rules and
constraints for XML documents.

An XSD defines the structure of an XML document. It specifies the elements and attributes
that can appear in an XML document and the type of data these elements and attributes can
contain. This information is used to verify that each element or attribute in an XML document
adheres to its description.

The purpose of an XML Schema is to define the legal building blocks of an XML document:
 the elements and attributes that can appear in a document
 the number of (and order of) child elements
 data types for elements and attributes
 default and fixed values for elements and attributes

Advantages of XSD over DTD


Following are the advantages of XSD over Document Type Definition (DTD):
1. XSD is extensible. You can derive new elements from the existing elements. DTD is not
extensible.
2. XSD is defined in XML. It does not require intermediate processing by a parser. DTD is
not defined in XML. You need separate parsers for DTD and XML.
3. XSD supports data types. You can restrict the content of an element. DTD does not
support data types. Therefore, you cannot restrict the content of an element.
4. XSD supports default values. You can specify default values of the elements. You cannot
specify the default values of elements in DTD.
5. XSD supports references to external XML schemas. You can include or import more than
one XML schema within an XML schema. You cannot include other DTDs within a
DTD.

Example:

By Lec. Teksan Gharti Page 14


XML Without XSD
The following is a simple XML file that contains some information about the three brightest stars
at night.

As you can see, we want to share the name, magnitude, and distance of these stars.
However, each of these pieces of information is rather special:
1. The first one is text
2. The second one is a decimal
3. The third one is an integer
So, it's much better to make sure over our data.

XML with XSD


XSD files are made up of tags, just like an XML file. In fact, XSD files actually are XML
files. Like an XML file, an XSD file has elements, and each element must have a name and a
type. There are simple, complex, and custom (user-defined) types. A simple element looks like
this:

As you can see, all we need is a name for the element (to distinguish it) and a type to
indicate what kind of element we can expect. Now when a user accesses the 'magnitude' piece of
data, it will always be checked to make sure it's a decimal (not a string or an integer). There are
many predefined types, such as string, integer, and decimal.

We could just define our ''brightstar'' schema with all simple elements, since all we need
are predefined types. Here is an example:

By Lec. Teksan Gharti Page 15


<xs:element name= “brightstar”>
<xs:complexType>
<xs:sequence>
<sx:element name “name” type= “xs:string”/>
<sx:element name “magnitude” type= “xs:decimal”/>
<sx:element name “distance” type= “xs:integer”/>
</xs:sequence>
</xs:complexType>
</xs:element name= “brightstar”>

XSD Elements and Attributes


An XML schema defines elements and their structures. It also defines the attributes and
their data types. The elements' structures can be of simpleType or complexType, depending on
whether the element is a leaf element or a parent element.

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

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

Here, element name is name of element, type is the data type like, integer, float, double, string
etc.

XSD elements can be of type simpleType, complexType, or anyType.


 An element of type simpleType contains only text. It cannot have attributes and elements.
 An element of type complexType can contain text, elements, and attributes.
 An element of type complexType is parent to all the elements and attributes contained
within it. An any element in an XSD specifies that any well-formed XML is allowed in
its place in XML instance.

Elements can be local or global. An element declared as the direct child of an XML
schema is called a global element and can be used throughout the schema. Elements declared
within a complex type definition are local elements. So, you cannot use these elements anywhere
else in the schema.

XSD Attributes

By Lec. Teksan Gharti Page 16


Attributes in XSD provide extra information within an element. Attributes
have name and type property. XSD attributes are always of type simpleType. The syntax for
defining an attribute is:

<xs:attribute name="myattribute" type="string"/>

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

In this example, myattribute is an attribute of data type string. An attribute can have a
fixed or default value.

Default and Fixed Values for Attributes


 Attributes may have a default value OR a fixed value specified.
 A default value is automatically assigned to the attribute when no other value is specified.
 In the following example the default value is "EN":

<xs:attribute name="lang" type="xs:string" default="EN"/>

 A fixed value is also automatically assigned to the attribute, and you cannot specify
another value.
 In the following example the fixed value is "EN":

<xs:attribute name="lang" type="xs:string" fixed="EN"/>

XSD Restrictions and Facets


 When an XML element or attribute has a data type defined, it puts restrictions on the
element's or attribute's content.
 If an XML element is of type "xs:date" and contains a string like "Hello World", the
element will not validate.
 Facets: Restrictions are used to define acceptable values for XML elements or attributes.
With XML Schemas, you can also add your own restrictions to your XML elements and
attributes. These restrictions are called facets.

Restrictions on Values

By Lec. Teksan Gharti Page 17


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

Restrictions on a Set of Values


To limit the content of an XML element to a set of acceptable values, we would use the
enumeration constraint.
The example below defines an element called "car" with a restriction. The only acceptable values
are: Audi, Golf, BMW:
<xs:element name="car">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Audi"/>
<xs:enumeration value="Golf"/>
<xs:enumeration value="BMW"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

Restrictions on a Series of Values (XML Patterns)


To limit the content of an XML element to define a series of numbers or letters that can be
used, we would use the pattern constraint.

The example below defines an element called "letter" with a restriction. The only acceptable
value is ONE of the LOWERCASE letters from a to z:
<xs:element name="letter">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[a-z]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
The next example defines an element called "initials" with a restriction. The only
acceptable value is THREE of the UPPERCASE letters from a to z:

By Lec. Teksan Gharti Page 18


<xs:element name="initials">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z][A-Z][A-Z]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

The next example also defines an element called "initials" with a restriction. The only acceptable
value is THREE of the LOWERCASE OR UPPERCASE letters from a to z:
<xs:element name="initials">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[a-zA-Z][a-zA-Z][a-zA-Z]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

The next example defines an element called "choice" with a restriction. The only acceptable
value is ONE of the following letters: x, y, OR z:
<xs:element name="choice">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[xyz]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

The next example defines an element called "prodid" with a restriction. The only acceptable
value is FIVE digits in a sequence, and each digit must be in a range from 0 to 9:
<xs:element name="prodid">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9][0-9][0-9][0-9][0-9]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

Restrictions on Length
To limit the length of a value in an element, we would use the length, maxLength, and
minLength constraints.
By Lec. Teksan Gharti Page 19
This example defines an element called "password" with a restriction. The value must be exactly
eight characters:
<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:length value="8"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

This example defines another element called "password" with a restriction. The value must be
minimum five characters and maximum eight characters:
<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="5"/>
<xs:maxLength value="8"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

Order Indicators:
We can control HOW elements are to be used in documents with indicators.
There are seven indicators:
Order indicators:
 All
 Choice
 Sequence
Occurrence indicators:
 maxOccurs
 minOccurs
Group indicators:
 Group name
 attributeGroup name

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

By Lec. Teksan Gharti Page 20


All Indicator:
The <all> indicator specifies that the child elements can appear in any order, and that each child
element must occur only once:
<xs:element name="person">
<xs:complexType>
<xs:all>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:all>
</xs:complexType>
</xs:element>
Note: When using the <all> indicator you can set the <minOccurs> indicator to 0 or 1 and the
<maxOccurs> indicator can only be set to 1.

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

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

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

By Lec. Teksan Gharti Page 21


Note: For all "Order" and "Group" indicators (any, all, choice, sequence, group name, and group
reference) the default value for maxOccurs and minOccurs is 1.

maxOccurs Indicator:
The <maxOccurs> indicator specifies the maximum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" maxOccurs="10"/>
</xs:sequence>
</xs:complexType>
</xs:element>
The example above indicates that the "child_name" element can occur a minimum of one time
(the default value for minOccurs is 1) and a maximum of ten times in the "person" element.

minOccurs Indicator:
The <minOccurs> indicator specifies the minimum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string"
maxOccurs="10" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
The example above indicates that the "child_name" element can occur a minimum of zero times
and a maximum of ten times in the "person" element.

Note: To allow an element to appear an unlimited number of times, use the


maxOccurs="unbounded" statement:

Example:
An XML file called "Myfamily.xml":
By Lec. Teksan Gharti Page 22
<?xml version="1.0" encoding="UTF-8"?>
<persons xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:noNamespaceSchemaLocation="family.xsd">
<person>
<full_name>Hege Refsnes</full_name>
<child_name>Cecilie</child_name>
</person>
<person>
<full_name>Tove Refsnes</full_name>
<child_name>Hege</child_name>
<child_name>Stale</child_name>
<child_name>Jim</child_name>
<child_name>Borge</child_name>
</person>
<person>
<full_name>Stale Refsnes</full_name>
</person>
</persons>

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

Here is the schema file "family.xsd":


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

<xs:element name="persons">
<xs:complexType>
<xs:sequence>
<xs:element name="person" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string"
minOccurs="0" maxOccurs="5"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
By Lec. Teksan Gharti Page 23
</xs:complexType>
</xs:element>
</xs:schema>

Group Indicators
Group indicators are used to define related sets of elements.

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

You must define an all, choice, or sequence element inside the group declaration. The following
example defines a group named "persongroup", that defines a group of elements that must occur
in an exact sequence:
<xs:group name="persongroup">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="birthday" type="xs:date"/>
</xs:sequence>
</xs:group>

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

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

<xs:complexType name="personinfo">
<xs:sequence>
<xs:group ref="persongroup"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
By Lec. Teksan Gharti Page 24
Attribute Groups:
Attribute groups are defined with the attributeGroup declaration, like this:
<xs:attributeGroup name="groupname">
...
</xs:attributeGroup>

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


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

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

<xs:element name="person">
<xs:complexType>
<xs:attributeGroup ref="personattrgroup"/>
</xs:complexType>
</xs:element>

Schema Element Types:


We can define XML schema elements in the following ways:

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

Complex Type:

By Lec. Teksan Gharti Page 25


A complex type is a container for other element definitions. This allows you to specify which
child elements an element can contain and to provide some structure within your XML
documents.
For example:
<xs:element name = "Address">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
In the above example, Address element consists of child elements. This is a container for
other <xs:element> definitions, that allows to build a simple hierarchy of elements in the XML
document.

Global Types:
With the global type, you can define a single type in your document, which can be used by all
other references. For example, suppose you want to generalize the person and company for
different addresses of the company. In such case, you can define a general type as follows:
<xs:element name = "AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>

Now let us use this type in our example as follows


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

By Lec. Teksan Gharti Page 26


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

Instead of having to define the name and the company twice (once for Address1 and once
for Address2), we now have a single definition. This makes maintenance simpler, i.e., if you
decide to add "Postcode" elements to the address, you need to add them at just one place.
Example1.xml
<?xml version = "1.0" encoding = "UTF-8" ?>
<book xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance

xsi:noNamespaceSchemaLocation="Example1.xsd">

<book1>
<name>math</name>
<author> Mr. Dravid &amp; Mr. Richard</author>
<price> Rs. 1000 </price>
</book1>
<book2>
<name>Science</name>
<author> Mr. Rahul</author>
<price> Rs. 1500 </price>
</book2>
</book>

Example1.xsd
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="book">
<xs:complexType>
<xs:sequence>
<xs:element name="book1">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="name"/>
<xs:element type="xs:string" name="author"/>
<xs:element type="xs:string" name="price"/>

By Lec. Teksan Gharti Page 27


</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="book2">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="name"/>
<xs:element type="xs:string" name="author"/>
<xs:element type="xs:string" name="price"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Exmple2.xml
<?xml version="1.0" encoding="utf-8"?>
<students xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance

xsi:noNamespaceSchemaLocation="Example2.xsd">

<student1>
<name> rahul </name>
<address type="permanent"> Butwol-1, Rupandehi </address>
<address type="temporary"> Gothatar-9, KTM </address>
<phone> 9876543234 </phone>
<website>www.rahul.com</website>
</student1>
</students>

Example2.xsd
<xs:schema
attributeFormDefault="unqualified"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="students">
<xs:complexType>
<xs:element name="student1">
<xs:complexType>

By Lec. Teksan Gharti Page 28


<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" minOccurs="1" maxOccurs="2"/>
<xs:attribute name="type" type="xs:string" use="required"/>
</xs:element>
<xs:element name="phone">
<xs:simpleType>
<xs:restriction base="integer">
<xs:length value="10"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="website" type="xs:anyURI"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:complexType>
</xs:element>

Example
<?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>

Document Type Definition (DTD)

By Lec. Teksan Gharti Page 29


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

In short…
 DTD stands for Document Type Definition.
 It is used to validate the XML documents.
 XML provides facility to create your own DTDs for XML document.
 DTD specifies the structure of the XML document.
 DTD is part of the file or separate document file.

Hence, the purpose of a DTD is to define the legal building blocks of an XML
document. It defines the document structure with a list of legal elements. A DTD can be declared
inline in your XML document, or as an external reference.

Syntax:
<!DOCTYPE element DTD identifier
[
declaration1
declaration2
........
]>
Here,
 The DTD starts with <!DOCTYPE delimiter.
 An element tells the parser to parse the document from the specified root element.
 DTD identifier is an identifier for the document type definition, which may be the path
to a file on the system or URL to a file on the internet. If the DTD is pointing to external
path, it is called External Subset.
 The square brackets [ ] enclose an optional list of entity declarations called Internal
Subset.

Types of DTD

By Lec. Teksan Gharti Page 30


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

There are two types of DTDs:


a) Internal DTD.
b) External DTD.

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

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

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

Example
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Teksan</name>
<company>Reliance</company>
<phone>(011) 123-4567</phone>
</address>
Output:

Code Explanation:

By Lec. Teksan Gharti Page 31


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

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

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

<!DOCTYPE address [
The DOCTYPE declaration has an exclamation mark (!) at the start of the element name.
The DOCTYPE informs the parser that a DTD is associated with this XML document.
DTD Body:
The DOCTYPE declaration is followed by DTD Body, where you declare elements,
attributes, entities, and notations.

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


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

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

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

Rules
 The document type declaration must appear at the start of the document (preceded only
by the XML header) − it is not permitted anywhere else within the document.
 Similar to the DOCTYPE declaration, the element declarations must start with an
exclamation mark.
 The Name in the document type declaration must match the element type of the root
element.

Example 2: Internal DTD

By Lec. Teksan Gharti Page 32


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE student [
<!ELEMENT student (firstname,lastname,school)>
<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT school (#PCDATA)>
]>
<student>
<firstname>Mark</firstname>
<lastname>Wood</lastname>
<school>Hills College</school>
</student>

In the above example,


 !DOCTYPE student indicates the beginning of the DTD declaration. And the student is
the root element of the XML document.
 !ELEMENT student indicates the student element must contain firstname,
lastname and school elements.
 !ELEMENT firstname indicates the firstname element is of
type #PCDATA (Parsed Character Data).
 !ELEMENT lastname indicates the lastname element is of type #PCDATA.
 !ELEMENT school indicates the school element is of type #PCDATA.

External DTD
This type of DTD is declared outside the XML file with a separate file. External DTD
is used in multiple XML documents, the updation done in this file affects all the XML document.

In external DTD the ‘standalone’ keyword is set to “no”. The external content is
specified using a keyword ‘PUBLIC’ and ‘SYSTEM’. The public keyword is used outside the
XML document followed by a URL (specifies the path).

Note: Multiple DTDs are allowed in which both external and internal DTDs are combined.

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

Example :1 – External DTD

By Lec. Teksan Gharti Page 33


Here the DTD file is created external and saved as stck.dtd and the corresponding
element name is declared in the separate XML file.

stck.dtd
<?xml version="1.0"?>
<!ELEMENT Stockmarket (sname,branch,contact)>
<!ELEMENT sname (#PCDATA)>
<!ELEMENT branch (#PCDATA)>
<!ELEMENT contact (#PCDATA)>

XML file

vision.xml
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
<!DOCTYPE Stockmarket SYSTEM "stck.dtd">
<Stockmarket>
<sname>Bluechip tech</sname>
<branch>nine</branch>
<contact>(022) 245-8597</contact>
</Stockmarket>

Output:

There are two types of External DTD: Private and public.


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

System Identifiers / Private External Declaration


A system identifier enables you to specify the location of an external file containing DTD
declarations. Syntax is as follows:
<!DOCTYPE name SYSTEM "file_location">
As you can see it contains keyword SYSTEM and a URI reference pointing to the location of the
document.

Public Identifiers / Public External Declaration


Public identifiers provide a mechanism to locate DTD resources and are written as below:
By Lec. Teksan Gharti Page 34
<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">
As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public
identifiers are used to identify an entry in a catalog. Public identifiers can follow any format,
however, a commonly used format is called Formal Public Identifiers, or FPIs.

When to Use a DTD?


 With a DTD, independent groups of people can agree to use a standard DTD for
interchanging data.
 With a DTD, you can verify that the data you receive from the outside world is valid.
 You can also use a DTD to verify your own data.

When NOT to Use a DTD?


 XML does not require a DTD.
 When you are experimenting with XML, or when you are working with small XML files,
creating DTDs may be a waste of time.
 If you develop applications, wait until the specification is stable before you add a DTD.
Otherwise, your software might stop working because of validation errors.

DTD Elements:
In a DTD, elements are declared with an ELEMENT declaration.

Declaring Elements:
In a DTD, XML elements are declared with the following syntax:

<!ELEMENT element-name category>


or
<!ELEMENT element-name (element-content)>

Empty Elements:
Empty elements are declared with the category keyword EMPTY:
<!ELEMENT element-name EMPTY>

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

Elements with Parsed Character Data:


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

By Lec. Teksan Gharti Page 35


Example:
<!ELEMENT from (#PCDATA)>

Elements with any Contents:


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

Elements with Children (sequences)


Elements with one or more children are declared with the name of the children elements inside
parentheses:
<!ELEMENT element-name (child1)>
or
<!ELEMENT element-name (child1,child2,...)>
Example:
<!ELEMENT note (to,from,heading,body)>
When children are declared in a sequence separated by commas, the children must appear in the
same sequence in the document. In a full declaration, the children must also be declared, and the
children can also have children. The full declaration of the "note" element is:
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
Declaring Only One Occurrence of an Element
<!ELEMENT element-name (child-name)>
Example:
<!ELEMENT note (message)>
The example above declares that the child element "message" must occur once, and only once
inside the "note" element.

Declaring Minimum One Occurrence of an Element


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

By Lec. Teksan Gharti Page 36


Declaring Zero or More Occurrences of an Element
<!ELEMENT element-name (child-name*)>
Example:
<!ELEMENT note (message*)>
The * sign in the example above declares that the child element "message" can occur zero or
more times inside the "note" element.

Declaring Zero or One Occurrences of an Element


<!ELEMENT element-name (child-name?)>
Example:
<!ELEMENT note (message?)>
The ? sign in the example above declares that the child element "message" can occur zero or one
time inside the "note" element.

Declaring either/or Content


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

Declaring Mixed Content


<!ELEMENT note (#PCDATA|to|from|header|message)*>
The example above declares that the "note" element can contain zero or more occurrences of
parsed character data, "to", "from", "header", or "message" elements.

DTD Attributes:
In a DTD, attributes are declared with an ATTLIST declaration.

Declaring Attributes
An attribute declaration has the following syntax:
<!ATTLIST element-name attribute-name attribute-type attribute-value>

DTD example:
<!ATTLIST payment type CDATA "check">
XML example:
<payment type="check" />
The attribute-type can be one of the following:

Type Description

By Lec. Teksan Gharti Page 37


CDATA The value is character data

(en1|en2|..) The value must be one from an enumerated list

ID The value is a unique id

IDREF The value is the id of another element

IDREFS The value is a list of other ids

NMTOKEN The value is a valid XML name

NMTOKENS The value is a list of valid XML names

ENTITY The value is an entity

ENTITIES The value is a list of entities

NOTATION The value is a name of a notation

xml: The value is a predefined xml value

The attribute-value can be one of the following:


Value Explanation

value The default value of the attribute

#REQUIRED The attribute is required

#IMPLIED The attribute is optional

#FIXED value The attribute value is fixed

A Default Attribute Value


DTD:
<!ELEMENT square EMPTY>
<!ATTLIST square width CDATA "0">
Valid XML:
<square width="100" />
In the example above, the "square" element is defined to be an empty element with a "width"
attribute of type CDATA. If no width is specified, it has a default value of 0.

#REQUIRED

Syntax

By Lec. Teksan Gharti Page 38


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

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

#FIXED
Syntax
<!ATTLIST element-name attribute-name attribute-type #FIXED "value">

Example
DTD:
<!ATTLIST sender company CDATA #FIXED "Microsoft">
Valid XML:
<sender company="Microsoft" />
Invalid XML:
<sender company="W3Schools" />
Use the #FIXED keyword when you want an attribute to have a fixed value without allowing the
author to change it. If an author includes another value, the XML parser will return an error.

By Lec. Teksan Gharti Page 39


Enumerated Attribute Values
Syntax
<!ATTLIST element-name attribute-name (en1|en2|..) default-value>
Example
DTD:
<!ATTLIST payment type (check|cash) "cash">
XML example:
<payment type="check" />
Or
<payment type="cash" />
Use enumerated attribute values when you want the attribute value to be one of a fixed set of
legal values.

Features of DTD
Following are some important points that a DTD describes
 The elements that can appear in an XML document.
 The order in which they can appear.
 Optional and mandatory elements.
 Element attributes and whether they are optional or mandatory.
 Whether attributes can have default values.
Advantages of using DTD
 Documentation − You can define your own format for the XML files. Looking at this
document a user/developer can understand the structure of the data.
 Validation − It gives a way to check the validity of XML files by checking whether the
elements appear in the right order, mandatory elements and attributes are in place, the
elements and attributes have not been inserted in an incorrect way, and so on.

Disadvantages of using DTD


 It does not support the namespaces. Namespace is a mechanism by which element and
attribute names can be assigned to groups. However, in a DTD namespaces have to be
defined within the DTD, which violates the purpose of using namespaces.
 It supports only the text string data type.
 It is not object oriented. Hence, the concept of inheritance cannot be applied on the
DTDs.
 Limited possibilities to express the cardinality for elements.

XSL:

By Lec. Teksan Gharti Page 40


XSL stands for EXtensible Stylesheet Language. It is a styling language for XML
just like CSS is a styling language for HTML.

In HTML documents, tags are predefined but in XML documents, tags are not
predefined. World Wide Web Consortium (W3C) developed XSL to understand
and style an XML document, which can act as XML based Stylesheet Language.

An XSL document specifies how a browser should render an XML document.

Main parts of XSL Document


 XSLT: It is a language for transforming XML documents into various other
types of documents.
 XPath: It is a language for navigating in XML documents.
 XQuery: It is a language for querying XML documents.
 XSL-FO: It is a language for formatting XML documents.

XPath:

XPath is an XML path used for navigation through the HTML structure of the
page. It is a syntax or language for finding any element on a web page using XML
path expression. XPath can be used for both HTML and XML documents to find
the location of any element on a webpage using HTML DOM structure.

Syntax:

By Lec. Teksan Gharti Page 41


 //: Select current node.
 Tagname: Tagname of the particular node.
 @: Select attribute.
 Attribute: Attribute name of the node.
 Value: Value of the attribute.

Example:

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


<bookstore>
<book category = "Math">
<title lang="en">IIT Mathematics</title>
<author>A Das Gupta</author>
</book>
<book category = "Chemistry">
<title lang="en"> Inorganic chemistry for JEE</title>
<author>V K Jaiswal</author>
</book>
</bookstore>

The XML Code is a tree like structure as we can see in the above XML, the code
starts with the bookstore node that has a child node book and it is followed by an
attribute category whose value is ‘Math’. The book node has 2 child node
i.e. title and author.

To select the author element of the chemistry book, the following XPath will be
used:

/bookstore/book[@category='Chemistry']/author

Types of XPath:

 Absolute XPath
 Relative Xpath

By Lec. Teksan Gharti Page 42


Absolute XPath:

Absolute XPath uses the root element of the HTML/XML code and followed by all
the elements which are necessary to reach the desired element. It starts with the
forward slash ‘/’ .

Generally, Absolute XPath is not recommended because in future any of the web
element when added or removed then Absolute XPath changes.

Example:

/bookstore/book[@category='Chemistry']/author

Relative XPath;

In this, XPath begins with the double forward slash ‘//’ which means it can search
the element anywhere in the Webpage.

Generally Relative Xpath is preferred as they are not complete path from Root
node.

Example:

//input[@id = 'fakebox-input']

It select the tag whose name is input and attribute as fakebox-input.

XPath Functions:
 contains()
 Start-With()
 Text()

contains():

This Function is used to select the node whose specified attribute value contains
the specified string provided in the function argument.

Example:

//input[contains(@id, 'fakebox')]

By Lec. Teksan Gharti Page 43


starts-with():

This function is used to select the node whose specified attribute value starts with
the specified string value provided in the function arguments.

Example:

//input[starts-with(@id, 'fakebox')]

text():

This function is used to find the node having the exact match with the specified
string value in the function.

Example:

//td[text()='UserID']

Uses of AND and OR in XPath:

AND and OR are used to combine two or more conditions to find the node.

Example:

//input[@value = 'Log In' or @type = 'submit']


Following is the list of useful paths and expression to select any node/ list of nodes from an
XML document.

S.No. Expression & Description

node-name
1
Select all nodes with the given name "nodename"

/
2
Selection starts from the root node

//
3
Selection starts from the current node that match the selection

4 .

By Lec. Teksan Gharti Page 44


Selects the current node

..
5
Selects the parent of the current node

@
6
Selects attributes

student
7
Example − Selects all nodes with the name "student"

class/student
8
Example − Selects all student elements that are children of class

//student
9
Selects all student elements no matter where they are in the document

XML Style Sheets (XSLT)


Extensible Stylesheet Language Transformations (XSLT) is a language for transforming
Extensible Markup Language (XML) documents into other structured documents such as XML,
HTML, plain text etc, as similar to the way that CSS files are used to transform HTML
documents. This is done by using a style sheet defining template rules for transforming a given
input XML document into an appropriate output document with the help of an XSL processor.

XSLT transformations can take place either at the client or server side. The XSLT
processing model consists of one or more source XML documents, one or more XSL style
sheets, an XSL processor and one or more structured output documents.

How XSLT Works

By Lec. Teksan Gharti Page 45


An XSLT document is a well-formed XML document that contains template rules. Each
template rule has a pattern and a template. An XSLT processor is a software that applies a given
XSLT stylesheet to a given XML document and builds the output document.

An XSLT processor works as follows. It visits the XML document tree using a pre-order
traversal and compares each encountered tree node to the patterns of the template rules in the
stylesheet. If a match is found, the processor writes the template of the matched rule into the
output document. When all nodes have been visited, 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.

Example:
Library.xml

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


<?xml-stylesheet type="text/XSL" href="xslstylesheet.xsl" ?>
<library>

By Lec. Teksan Gharti Page 46


<book>
<title>Web Tech</title>
<author>raj</author>
<yearpublished>2021</yearpublished>
</book>
<book>
<title>Java</title>
<author>Vijay</author>
<yearpublished>2020</yearpublished>
</book>
</library>

xslstylesheet.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/library">
<html>
<body>
<h2>Book Collection</h2>
<table border="3" align= "center">
<tr>
<th>Title</th>
<th>Author</th>
<th>Year</th>
</tr>
<xsl:for-each select="library/book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select=" yearpublished "/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

By Lec. Teksan Gharti Page 47


Output:

XQuery
XQuery is a functional query language used to retrieve information stored in XML
format. It is same as for XML what SQL is for databases. It was designed to query XML data.
XQuery is built on XPath expressions. It is a W3C recommendation which is supported by all
major databases.

XQuery was devised primarily as a query language for data stored in XML form. So its
main role is to get information out of XML databases — this includes relational databases that
store XML data, or that present an XML view of the data they hold.

Some people are also using XQuery for manipulating free-standing XML documents, for
example, for transforming messages passing between applications. In that role XQuery competes
directly with XSLT, and which language you choose is largely a matter of personal preference.

XQuery FLWOR

FLWOR is an acronym which stands for "For, Let, Where, Order by, Return".

 For - It is used to select a sequence of nodes.


 Let - It is used to bind a sequence to a variable.
 Where - It is used to filter the nodes.
 Order by - It is used to sort the nodes.
 Return - It is used to specify what to return (gets evaluated once for every node).

Example

By Lec. Teksan Gharti Page 48


University.xml
<university>
<universityinfo>
<name>Tribhuvan university</name>
<location>balkhu</location>
<cources>
<name>BCA</name>
<faculty>humanities</faculty>
<cridit>3 hrs</cridit>
<system>semester wise</system>
</cources>
</universityinfo>
</university>

University.xqy
for $x in doc("university.xml")/university/universityinfo
return $x/name

Output:

DOM:
The Document Object Model (DOM) is the foundation of XML. XML documents have a
hierarchy of informational units called nodes; DOM is a way of describing those nodes and the
relationships between them.

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


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

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

Example:

<?xml version="1.0"?>
<books>
<book>

By Lec. Teksan Gharti Page 49


<author>Carson</author>
<price format="dollar">31.95</price>
<pubdate>05/01/2001</pubdate>
</book>
<pubinfo>
<publisher>MSPress</publisher>
<state>WA</state>
</pubinfo>
</books>
XML DOM tree structure of above xml code is:

XMLHttpRequest
All modern browsers have a built-in XMLHttpRequest object to request data from a server.

The XMLHttpRequest object can be used to request data from a web server.

The XMLHttpRequest object can perform following task

 Update a web page without reloading the page


 Request data from a server - after the page has loaded
 Receive data from a server - after the page has loaded
 Send data to a server - in the background

Sending an XMLHttpRequest using JavaScript

A common JavaScript syntax for using the XMLHttpRequest object looks much like this:

By Lec. Teksan Gharti Page 50


Example:

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {

if (this.readyState == 4 && this.status == 200) {

// Typical action to be performed when the document is ready:

document.getElementById("demo").innerHTML = xhttp.responseText;

};

xhttp.open("GET", "filename.xml", true);


xhttp.send();

The first line in the example above creates an XMLHttpRequest object:

var xhttp = new XMLHttpRequest();

The onreadystatechange property specifies a function to be executed every time the status of
the XMLHttpRequest object changes:

xhttp.onreadystatechange = function()

When readyState property is 4 and the status property is 200, the response is ready:

if (this.readyState == 4 && this.status == 200)

The responseText property returns the server response as a text string.

The text string can be used to update a web page:

document.getElementById("demo").innerHTML = xhttp.responseText;

By Lec. Teksan Gharti Page 51


Creating XML Parser
The XML DOM (Document Object Model) defines the properties and methods for accessing and
editing XML.

However, before an XML document can be accessed, it must be loaded into an XML DOM
object. All modern browsers have a built-in XML parser that can convert text into an XML
DOM object.

Parsing a Text String

Following example parses a text string into an XML DOM object, and extracts the info from it
with JavaScript.

Example:

<html>
<body>
<p id="demo"></p>
<script>
var text, parser, xmlDoc;
text = "<bookstore><book>" +
"<title>Web Technology</title>" +
"<author>John Diew</author>" +
"<year>2005</year>" +
"</book></bookstore>";

parser = new DOMParser();


xmlDoc = parser.parseFromString(text,"text/xml");

document.getElementById("demo").innerHTML =

By Lec. Teksan Gharti Page 52


xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
</script>
</body>
</html>

In the above example:

A text string is:

text = "<bookstore><book>" +
"<title>Web Technology</title>" +
"<author>John Diew</author>" +
"<year>2005</year>" +
"</book></bookstore>";

An XML DOM parser is created:

parser = new DOMParser();

The parser creates a new XML DOM object using the text string:

xmlDoc = parser.parseFromString(text,"text/xml");

The XMLHttpRequest Object


The XMLHttpRequest Object has a built in XML Parser.

The responseText property returns the response as a string.

The responseXML property returns the response as an XML DOM object.

If you want to use the response as an XML DOM object, you can use the responseXML
property.

document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;

Example: Create an xml file to store data and display data in html page

text.xml

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

By Lec. Teksan Gharti Page 53


<bookstore>
<book category="Tech">
<title lang="en">Web Technology</title>
<author>Florida Amanda</author>
<year>2005</year>
<price>30.00</price>
</book>

<book category="Account">
<title lang="en">Financial Account</title>
<author> John Diew </author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>

test.html

<!DOCTYPE html>
<html>
<body>
<b>First Author Name:</b><span id="first"> </span><br>
<b>Second Author Name:</b><span id="second"></span>

<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};

// readyState==4, means http request fineshed and response is ready


// status == 200,is process is successed or ok

xhttp.open("GET", "test.xml", true);


xhttp.send();

function myFunction(xml) {
var xmlDoc = xml.responseXML;
document.getElementById("first").innerHTML =
xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue;
document.getElementById("second").innerHTML =
xmlDoc.getElementsByTagName("author")[1].childNodes[0].nodeValue;

By Lec. Teksan Gharti Page 54


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

Output:

=======================End Unit 3======================================

By Lec. Teksan Gharti Page 55


By Lec. Teksan Gharti Page 56
<employees>
<employ

By Lec. Teksan Gharti Page 57

You might also like