Unit-3 The Client Tier
Unit-3 The Client Tier
====================================================================
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.
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.
<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>.
Syntax:
<element-name attributes> Contents...</element-name>
Above is the example of an XML document describing the address of a college student using
XML 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:
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 (“”).
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.
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.
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.
7. Comments in XML
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
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.
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.
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 …
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.
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.
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.
Example
<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
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 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.
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>
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
Example:
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.
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:
XSD Elements
Elements are the building blocks of XML document. An element can be defined within
an XSD as follows:
Here, element name is name of element, type is the data type like, integer, float, double, string
etc.
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
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.
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":
Restrictions on Values
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:
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.
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.
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.
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.
<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: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>
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>
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:
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>
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 & 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"/>
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>
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>
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
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:
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.
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.
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.
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:
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:
Empty Elements:
Empty elements are declared with the category keyword EMPTY:
<!ELEMENT element-name EMPTY>
Example:
<!ELEMENT br EMPTY>
XML example:
<br />
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
#REQUIRED
Syntax
#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.
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.
XSL:
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.
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:
Example:
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
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']
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')]
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']
AND and OR are used to combine two or more conditions to find the node.
Example:
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 .
..
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
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.
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
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>
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".
Example
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.
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>
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.
A common JavaScript syntax for using the XMLHttpRequest object looks much like this:
xhttp.onreadystatechange = function() {
document.getElementById("demo").innerHTML = xhttp.responseText;
};
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:
document.getElementById("demo").innerHTML = xhttp.responseText;
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.
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>";
document.getElementById("demo").innerHTML =
text = "<bookstore><book>" +
"<title>Web Technology</title>" +
"<author>John Diew</author>" +
"<year>2005</year>" +
"</book></bookstore>";
The parser creates a new XML DOM object using the text string:
xmlDoc = parser.parseFromString(text,"text/xml");
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
<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);
}
};
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;
Output: