XML Simplified
XML Simplified
XML Simplified
Learners Guide
No part of this book may be reproduced or copied in any form or by any means graphic, electronic or
mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent
or transferred without the prior written permission of copyright owner Aptech Limited.
APTECH LIMITED
Contact E-mail: [email protected]
Aptech Ltd. designs its courses using a sound instructional design model from conceptualization
to execution, incorporating the following key aspects:
Needs assessment is carried out to find the educational and training needs of the learner
Technology trends are regularly scanned and tracked by core teams at Aptech Ltd. TAG*
analyzes these on a monthly basis to understand the emerging technology training needs for
the Industry.
The skill requirements are then mapped with the learner profile (user system) to derive the
Learning objectives for the different roles.
The Learning objectives are then analyzed and translated into learning tasks. Each learning
task or activity is analyzed in terms of knowledge, skills and attitudes that are required to
perform that task. Teachers and domain experts do this jointly. These are then grouped in
clusters to form the subjects to be covered by the curriculum.
In addition, the society, the teachers, and the industry expect certain knowledge and skills
that are related to abilities such as learning-to-learn, thinking, adaptability, problem solving,
positive attitude etc. These competencies would cover both cognitive and affective domains.
A precedence diagram for the subjects is drawn where the prerequisites for each
subject are graphically illustrated. The number of levels in this diagram is determined
by the duration of the course in terms of number of semesters etc. Using the precedence
diagram and the time duration for each subject, the curriculum is organized.
The content outlines are developed by including additional topics that are required for the
completion of the domain and for the logical development of the competencies identified.
Evaluation strategy and scheme is developed for the subject. The topics are arranged/organized
in a meaningful sequence.
The detailed instructional material Training aids, Learner material, reference material, project
guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage.
Careful consideration is given for the integral development of abilities like thinking, problem
solving, learning-to-learn etc. by selecting appropriate instructional strategies (training
methodology), instructional activities and instructional materials.
The area of IT is fast changing and nebulous. Hence considerable flexibility is provided in the
instructional process by specially including creative activities with group interaction between
the students and the trainer. The positive aspects of web based learning acquiring information,
organizing information and acting on the basis of insufficient information are some of the
aspects, which are incorporated, in the instructional process.
Assessment of learning
The learning is assessed through different modes tests, assignments & projects. The
assessment system is designed to evaluate the level of knowledge & skills as defined by the
learning objectives.
*TAG Technology & Academics Group comprises members from Aptech Ltd., professors from
reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software
Majors & representatives from regulatory organizations/forums.
Technology heads of Aptech Ltd. meet on a monthly basis to share and evaluate the technology
trends. The group interfaces with the representatives of the TAG thrice a year to review and
validate the technology and academic directions and endeavors of Aptech Ltd.
Aptech New Products Design Model
Key Aspects
1
Evaluation of
Scanning the user
Instructional
system and needs
Processes and
assessment
Material
2 6
Need Analysis
Assessment of
and design of
learning
curriculum
3 Design and
5
Strategies for
development of
delivery of
instructional
instructions
material 4
Preface
In this book, XML Simplified, students will learn the fundamentals of XML. This book is an introduction
to XML that prepares students with a strong foundation in one of the key elements of Web programming,
that is, XML. The book describes and explains various features and concepts of XML.
This book is the result of a concentrated effort of the Design Team, which is continuously striving to bring
you the best and the latest in Information Technology. The process of design has been a part of the ISO
9001 certification for Aptech-IT Division, Education Support Services. As part of Aptechs quality drive,
this team does intensive research and curriculum enrichment to keep it in line with industry trends.
Design Team
Table of Contents
Sessions
1. Introduction to XML.......................................................................................................
2. Namespaces..................................................................................................................
3. DTDs.............................................................................................................................
4. XML Schema.................................................................................................................
5. Style Sheets..................................................................................................................
7. More on XSLT................................................................................................................
Introduction to XML
Concepts
Module Overview
Welcome to the module, Introduction to XML. The module describes drawbacks of earlier
markup languages that led to the development of XML. The module also explains the structure
and lifecycle of the XML document. This module covers more on the XML syntax and the various
parts of the XML document.
Introduction to XML
Exploring XML
XML Syntax
Early electronic formats like troff and TEX, were more concerned about the presentation of the content
rather than with document structure.
Markup languages are used to define the meaning and organize the structure of a text document. Markup
languages help the documents by giving them a new look and formatting the text.
Procedural Markup: Procedural markup is similar to presentation markup but in the former, the
user will be able to edit the text file. Here, the user is helped by the software to arrange the text.
These markup languages are used in professional publishing organizations.
Descriptive Markup: Descriptive markup is also known as semantic markup. This kind of markup
determines the content of the document.
Two types of markup languages are popular in recent times. They are as follows:
Generalized Markup Languages: These type of languages describe the structure and meaning
of the text in a document.
Specific Markup Languages: These type of markup languages are used to generate application
specific code.
Generalized Markup Language (GML), a project by IBM, helped the documents to be edited, formatted,
and searched by different programs using its content-based tags. Generalized Markup Language (GML)
was developed to accomplish the following:
The markup should describe only the structure of the document but not its flair.
The syntax of the markup language should be strictly followed so that the code can clearly be
read by a software program or by a human being.
In 1980, ANSI Committee created Standard Generalized Markup Language (SGML), an all-encompassing
coding scheme and flexible toolkit for developing specialized markup languages. Standard Generalized
Markup language (SGML) is the successor to GML. In 1986, International Organization for Standardization
(ISO) acquired it as a standard. SGML is a meta language as other languages are created from it.
SGML has a syntax to include markup in documents. SGML also has a syntax to describe what tags
are allowed in different locations. SGML application consists of SGML declaration and SGML Document
Type Definition (DTD).
In 1989, Hyper Text Markup Language (HTML), a technology for sharing information by using hyperlinked
text documents was developed. HTML (Hyper Text Markup Language) was created from SGML. In the
early years, it was extensively accessed by scientists and technicians. HTML was originally created
to mark up technical papers, so that they could be transferred across different platforms. However,
with time, it began to be used for marking up non-technical documents too. As the use of the Internet
became popular, browser manufacturers started developing different tags to display documents with
more creativity. But, this created problems for implementation in different browsers with the increase in
the number of tags used.
Concepts
Figure 1.1: Evolution of Markup Languages
Features
1. GML describes the document in terms of its format, structure, and other properties.
2. SGML ensures that the system can represent the data in its own way.
3. HTML used ASCII text, which allows the user to use any text editor.
Drawbacks
1. GML and SGML were not suited for data interchange over the Web.
2. HTML possesses instructions on how to display the content rather than the content they
encompass.
In order to address the issues raised by earlier markup languages, the Extensible Markup Language
(XML) was created. XML is a W3C recommendation.
XML is a set of rules for defining semantic tags that break a document into parts and identify the different
parts of the document. XML was developed over HTML because of the basic differences between them
given in table 1.1.
HTML XML
HTML was designed to display data. XML was designed to carry data.
HTML displays data and focuses on how data XML describes data and focuses on what data is.
looks.
HTML displays information. XML describes information.
XML tags are not predefined. You must define your own tags
Concepts
XML markup defines the physical and logical layout of the document. XML can be considered as an
information container. It contains shapes, labels, structures and also protects information. XML employs
a tree-based structure to represent a document. The basic foundation of XML is laid down by symbols
embedded in the text known as markup. The markup combines the text and extra information about the
text like its structure and presentation. The markup divides the information into a hierarchy of character
data and container-like elements and its attributes. A number of software programs process electronic
documents use a markup.
The underlying unit of XML is a character. The combination of characters is known as an entity. These
entities are either present in the entity declaration or in a text file stored externally. All the characters are
grouped together to form an XML document.
XMLs markup divides a document into separate information containers called elements. A document
consists of one outermost element called root element that contains all the other elements, plus some
optional administrative information at the top, known as XML declaration. The following code demonstrates
the elements.
Code Snippet:
where,
<Name>, <Price>, <Description> and <Number> inside the tags are elements.
The usage of XML can be observed in many real-life scenarios. It can be used in the fields of information
sharing, single application usage, content delivery, re-use of data, separation of data and presentation,
semantics, and so forth. News agencies are a common place where XML is used. News producers and
news consumers often use a standard specification named XMLNews to produce, retrieve, and relay
information across different systems in the world.
Note: XML is a subset of SGML, with the same goals, but with as much of the complexity eliminated
as possible. This means that any document which follows XMLs syntax rules will also follow SGMLs
syntax rules, and can therefore be read by existing SGML tools.
Data independence
Data independence is the essential characteristic of XML. It separates the content from its
presentation. Since an XML document describes data, it can be processed by any application.
Easier to parse
The absence of formatting instructions makes it easy to parse. This makes XML an ideal framework
for data exchange.
Because XMLs semantic and structural information enables it to be manipulated by any application,
much of the processing that was once earlier limited to servers can now be performed by clients.
This reduces server load and network traffic, resulting in a faster, more efficient Web.
Easier to create
It is text-based, so it is easy to create an XML document with even the most primitive text processing
tools. However, XML also can describe images, vector graphics, animation or any other data type
to which it is extended.
The W3C uses XML to write its specifications and transforms it to a number of other presentation
formats. Some Web sites also use XML for their content and get it transformed to HTML using
XSLT and CSS and display the content directly in browsers.
XML is also used as a protocol for Remote Procedure Calls (RPC). RPC is a protocol that allows
objects on one computer to call objects on another computer to do work, allowing distributed
computing.
e-Commerce
XML can be used as an exchange format in order to send data from one company to another.
Note: The process of manipulating an XML document is called as XML Parsing. The parser loads the
Concepts
document into the memory. After the document is loaded into the memory, Document Object Model
(DOM) manipulates the data.
Even though XML has many advantages, it has a few disadvantages too. Some of the disadvantages are
as follows:
Usage of XML leads to increase in data size and processing time. Since XML uses Unicode
encoding set for characters, it also consumes more memory.
XML lacks adequate amount of processing instructions. If the process of translation is not used,
then the developers globally are forced to prepare their own processing instructions to display
XML in the required form.
Versions of Internet Explorer (IE) earlier than 5.0 do not support XML.
Knowledge Check 1
1. Which of the following statements are true and which are false in the case of XML?
2. Which of the statements about XML are true and which of the statements are false?
State the functions of editors for XML and list the popularly used editors.
State the functions of parsers for XML and list names of commonly used parsers.
State the functions of browsers for XML and list the commonly used browsers.
XML documents are commonly stored in text files with extension .xml. The two sections of an XML
document are:
Document Prolog: XML parser gets information about the content in the document with the help
of document prolog. Document prolog contains metadata and consists of two parts - XML
Declaration and Document Type Declaration. XML Declaration specifies the version of XML being
used. Document Type Declaration defines entities or attributes values and checks grammar and
vocabulary of markup.
Root Element: The second is an element called the root element. The root element is also called
a document element. It must contain all the other elements and content in the document. An XML
element has a start tag and end tag.
Sibling: They are elements which have the same parent element.
An XML document consists of a set of unambiguously named "entities". Every XML document starts with
a "root" or document entity. All other entities are optional. Entities are aliases for more complex functions.
A single entity name can represent a large amount of text. The alias name is used each time some text
is referenced and the processor expands the contents of the alias.
Concepts
Figure 1.3: XML Document Structure
Code Snippet:
where,
Concepts
The first block indicates xml declaration and document type declaration. Music_Library is the root
element.
The logical structure of an XML document gives information about the elements and the order in which
they are to be included in the document. It shows how a document is constructed rather than what it
contains.
Document Prolog forms the basis of the logical structure of the XML document. XML Declaration and
Document Type Definition are its two basic and optional components as shown in figure 1.4.
Code Snippet:
XML Declaration gives the version of the XML specification and also identifies the character encoding
scheme.
Concepts
Code Snippet:
A document type definition defines a set of rules to which the XML document conforms. A DTD can be
either external or internal. In this case, the DTD is an external file.
An XML editor refers to the DTD and creates an XML document. After the document is created, the
document is scanned for elements and attributes in it. This stage is known as scanning. The XML parser
builds a complete data structure after parsing. The data is then extracted from elements and attributes
of the document. This stage is known as access. It is then converted into the application program. The
document structure can also be modified during the process by inserting or deleting elements or by
changing textual content of element or attribute. This stage is known as modification. The data is then
serialized to a textual form and is passed to a browser or any other application that can display it. This
stage is known as serialization.
Note: XML parser creates, manipulates and updates the XML document. It will read the list of records in
the XML document and the handler stores it in the form of a data structure. The handler then processes
it and displays it in HTML.
1.2.4 Editors
An XML Editor is used to create and edit XML documents. Any application can be used as an editor
in XML. Since all XML documents are text-based markup languages, a standard Windows Notepad
or Wordpad can also be used. However, for various reasons, Notepad should not be used for writing
professional XML. Notepad does not know that the text written in it is XML code, and thus, can create
problem. For an XML document to be error-free and possess XML-specific features, like the ability to edit
elements and attributes, a professional XML editor should be used.
XMLwriter
XML Spy
XML Pro
XMLmind
XMetal
1.2.5 Parsers
An XML parser/XML processor reads the document and verifies it for its well-formedness.
An XML parser keeps the entire representation of XML data in memory with the help of Document Object
Model (DOM). The in-built parser used in IE 5.0 is also known as Microsoft XML Parser (MSXML). It is a
component, which is available once IE 5.0 is installed.
Microsofts XML parser goes through the entire data structure and accesses the values of the attributes in
the elements. The parser also creates or deletes the elements and converts the tree structure into XML.
Concepts
MSXML 3.0 supports XSL transformations, which contain data manipulation operations. The XML parsers
ignore the white space by default, but if the default value of Boolean preserveWhiteSpace property of
DOMDocument object is true, the XML parsers preserve the white space. Using Microsoft Data type
Schema, MSXML 3.0 specifies a data type for the element or the attribute. MSXML also improves the
performance of the applications with the help of different caching features.
XML parsing in Mozilla performs functions like going through the elements, accessing their values, and
so on. Using JavaScript, an instance of XML parser can be created in Mozilla browsers. The XML parsing
in Firefox automatically parses the data into Document Object Model (DOM). Opera uses only those XML
parsers that do not validate DTDs by default.
Speed and performance are the criteria against which XML parsers are selected.
Crimson
Xerces
MSXML
yy Reads the document and checks for its conformity with XML standards.
Validating parser
1.2.6 Browsers
Concepts
After the XML document is read, the parser passes the data structure to the client application. The
application can be a Web browser. The browser then formats the data and displays it to the user. Other
programs like database, MIDI program or a spreadsheet program may also receive the data and present
it accordingly.
The final output of XML data is viewed in a browser. XML is not supported by all browsers, for example,
Netscape Navigator 4.0 does not support XML but later versions of the browser like Netscape 6.0 do
support it. Only browsers like IE 5.0 or greater give full support for XML specifications. In IE, XML can be
directly viewed using style sheets. It gives support to namespaces and handles a mechanism known as
data islands where XML is embedded into HTML.
Mozilla 5.0 uses an interface to the XML DOM (Document Object Model) via JavaScript and plug-ins. It
also supports elements from the HTML namespace.
Netscape
Mozilla
Internet Explorer
Firefox
Opera
Knowledge Check 2
1. Which of the statements about the structure of XML documents are true and which statements are
false?
2. Which of the characteristics are true or false accordingly when an XML document is created by an
XML editor?
Concepts
(A) XML syntax is colored.
(B) XML is not validated.
(C) XML parser reads the document after it is created.
(D) XML is transformed only via XSLT.
(E) XML document is edited by keeping DTD in mind.
3. Which of the statements about XML browsers and parsers are true and which statements are
false?
In this third lesson, Working with XML, you will learn to:
2. DTD or Schema
To create a simple XML document, you type XML code in any text or XML editor as demonstrated
in the following code.
Code Snippet:
After the typing is done, you save the contents of the file. To save the file, you click the File menu,
click the "Save" option and provide the file name such as, for example, SoftDrink.xml. The
extension .xml is compulsory if you are typing the code in Notepad or any kind of word processor
such as Microsoft Word.
After the document is saved, you can open the file directly in a browser that supports XML. A
common browser used is Internet Explorer 5.0 or later.
Concepts
Figure 1.6: XML Document
<?xml
The XML declaration should start with the five character string, <?xml. It indicates that the document is
an XML document.
version="1.0"
The XML declaration tells the version of XML, the type of character encoding being used and the markup
declaration used in the XML document.
encoding="iso-8859-1"
Characters are encoded using various encoding formats. The character encoding is declared in encoding
declaration.
standalone="yes"
The standalone declaration indicates the presence of external markup declarations. "Yes" indicates that
there are no external markup declarations and "no" indicates that external markup declarations might
exist.
The Document Type Declaration declares and defines the elements used in the document class. This is
a DTD used internally as demonstrated in the following code:
Concepts
<!DOCTYPE Student [
<!ELEMENT Student (Name,Dob,BloodGroup,RollNumber)>
<!ELEMENT Name (#PCDATA)>
<!ELEMENT Dob (#PCDATA)>
<!ELEMENT BloodGroup (#PCDATA)>
<!ELEMENT RollNumber (#PCDATA)>
]>
This part defines the content of the XML document called as markup. It describes the purpose and
function of each element.
Note: The tags in XML are not predefined. XML allows the user to create the tags when needed.
<?xml version="1.0" encoding="iso-8859-1"?>
<Message>
Please Call
</Message>
The two XML code snippets listed show the same output with different names. They are equal as they
have the same structure and content.
Concepts
Markup can be divided into following three parts:
Structure
It describes the form of the document by specifying the relationship between different elements
in the document. It emphasizes to specify a single non-empty, root element that contains other
elements and the content.
Semantic
Semantics describes how each element is specified to the outside world of the document. For
example, an HTML enabled Web browser assigns "paragraph" to the tags <P> and </P> but not to
the tags <Message> and </Message>.
Style
It specifies how the content of the tag or element is displayed. It indicates whether the tag is bold,
normal, and pink in color or with the font size 10.
Well-formedness refers to the standards that are to be followed by the XML documents. Well-formedness
makes XML processors and browsers read XML documents. A document is well formed, if it fulfills the
following rules:
Every well formed XML document should consist of a minimum of one element.
All the tags used are case sensitive, that is <URGENT> is different from <urgent>.
All the tags in XML should begin with a start tag and a matching end tag. The end tags only have
an additional forward slash as compared to their start tag.
All the XML tags used should be nested properly. The following code demonstrates this property.
Code Snippet:
<Book>
<Name>Good XML</Name>
<Cost>$20</Cost>
</Book>
yy Tags should contain combination of letters, numbers, periods (.), colons, underscores, or
hyphens (-).
yy Attributes are specified by a name and value pair which is delimited by equal (=) sign. The
values are delimited by quotation marks. For example,
To be read by the XML browsers, the document should be checked against the XML rules.
Concepts
Figure 1.7: Well-formed XML Document
Knowledge Check 3
Concepts
Concepts
<Matter>
<Wish> Hi, </Wish>
<Body> The test is on Wednesday. </Body>
<Close>
Regards
(C)
Sam.
</Close>
<Date>
<Day>12</Day>
<Month>2</Month>
<Year>2007</Year>
<Date></Matter>
<?xml version="1.0" encoding="iso-8859-1"?>
<Matter>
Hi,
<Body> The test is on Wednesday. </Body>
<Close>
Regards
(D)
Sam.
</Close>
<Date>
<Day>12</Day>
<Month>2</Month>
<Year>2007</Year>
<Date></Matter>
Concepts
In this last lesson, XML Syntax, you will learn to:
State and describe the use of comments and processing instructions in XML.
1.4.1 Comments
XML comments are used for the people to give information about the code in the absence of the developer.
It makes a document more readable. Comments are not restricted to document type definitions but may
be placed anywhere in the document. Comments in XML are similar to those in HTML. Comments should
be used only when needed, as they are not processed. Comments are used only for human consumption
rather than machine consumption. Since the comments are not parsed, their presence or absence does
not make any difference to the processors.
They are inserted into the XML document and are not part of the XML code. They can appear in the
document prolog, DTD or in the textual content. These comments will not appear inside the tags or
attribute values.
Comments start with the string <!-- and end with the string -->. The parser believes that the comment
has come to an end when it finds a > as shown in figure 1.8.
Rules
The rules that are to be followed while writing the comments are as follows:
yy Comments should not include "-" or "" as it might lead to confuse the XML parser.
Code Snippet:
<Name NickName=John>
<First>John</First>
<!--John is yet to pay the term fees-->
<Last>Brown</Last>
<Semester>Final</Semester>
</Name>
Concepts
Processing instructions are information which is application specific. These instructions do not follow
XML rules or internal syntax. With the help of a parser these instructions are passed to the application.
The application can either use the processing instructions or pass them on to another application.
The main objective of a processing instruction is to present some special instructions to the application.
All processing instructions must begin with <? and end with ?>.
Though an XML declaration also begins with <? and end with ?>, it is not considered as a processing
instruction. It is because an XML declaration provides information only for the parsers and not for the
application. In some cases, the application might need the information in the processing instruction only
if it displays the output to the user.
Syntax:
<?PITarget <instruction>?>
where,
PITarget is the name of the application that should receive the processing instructions.
Code Snippet:
<Name NickName=John>
<First>John</First>
<!--John is yet to pay the term fees-->
<Last>Brown</Last>
<?feesprocessor SELECT fees FROM STUDENTFEES?>
<Semester>Final</Semester>
</Name>
where,
feesprocessor is the name of the application that receives the processing instruction.
Character data describes the documents actual content with the white space. The text in character
data is not processed by the parser and thus, not treated as a regular text. The character data can be
classified into:
CDATA
PCDATA
1.4.4 PCDATA
The data that is parsed by the parser is called as parsed character data (PCDATA). The PCDATA specifies
that the element has parsed character data. It is used in the element declaration.
Escape character like "<" when used in the XML document will make the parser interpret it as a new
element. As a result it will generate an error as shown in figure 1.9.
Concepts
Code Snippet:
<Name nickname=John>
<First>John</First>
<!--John is yet to pay the term fees-->
<Last>Brown</Last>
<Semester>Final> 10 & <20</Semester>
</Name>
1.4.5 CDATA
CDATA stands for character data that has reserved and white space characters in it. Though the text
inside the CDATA is not parsed by the parser, it is commonly used for scripting code. XML parser ignores
all tags and entity references inside the CDATA blocks. The CDATA block indicates to the parser that it is
just a text but not a markup. A CDATA block always begins with the delimiter <![CDATA[ and ends with
the delimiter ]]>. Since the ending delimiter marks the end of the CDATA block, the character string ]]/
is not allowed in the middle of the CDATA block. This will signal the end of the CDATA section.
Code Snippet:
<Sample>
<![CDATA[
<Document>
<Name>Core XML</Name>
<Company>Aptech</Company>
</Document>]]>
</Sample>
1.4.6 Entities
Concepts
The XML document is made up of large amount of information called as entities. Entities are used to avoid
typing long pieces of text repeatedly, within the document. They can be categorized into the following:
Character entities: They form the mechanism, which is used in place of a characters literal form.
They provide the meaning of > when the symbol > is typed. Character entities can also be
used with decimal or hexadecimal values with a condition that the numbers support Unicode
coding. An XML processing program replaces character entities with their equivalent characters.
Content entities: These entities are used to replace certain values. They are similar to text
substitution macros in programming languages such as C. Content entity has the following syntax:
Unparsed entities: These entities when used, turn off the parsing process. They can be used to
include multimedia content in the XML document.
Every entity consists a name and a value. The value ranges from a single character to a XML markup
file. As the XML document is parsed, it checks for entity references. For every entity reference, the parser
checks the memory to replace the entity reference with a text or markup.
An entity reference consists of an ampersand (&), the entity name, and a semicolon (;).
All the entities must be declared before they are used in the document. An entity can be declared either
in a document prolog or in a DTD.
Some of the entities are defined in the system and are known as pre-defined entities. These entities are
described in table 1.2.
Concepts
Code Snippet:
<?xml version="1.0"?>
<!DOCTYPE Letter [
<!ENTITY address "15 Downing St Floor 1">
<!ENTITY city "New York">
]>
<Letter>
<To>"Tom Smith"</To>
<Address>&address;</Address>
<City>&city;</City>
<Body>
Hi! How are you?
The sum is > $1000
</Body>
<From>ARNOLD</From>
</Letter>
Entities are used as shortcuts to refer to the data pages. Figure 1.10 shows the entity categories.
General Entity
These are the entities used within the document content. General entities can either be declared
internally or externally. The references for general entities start out with an ampersand (&) and end
with a semicolon (;). The entitys name is present within these two characters.
Every internal general entity is defined in the DTD. It is declared with the keyword <!ENTITY>. The
syntax is as follows:
where,
External entities refer to the storage units outside the document containing the root element. Using
external entity references, external entities can be embedded inside the document. An external
entity reference indicates the location where the parser should insert the external entity in the
document. The external entity has Uniform Resource Locator (URL) in its declaration; the URL
specified indicates the document where the text of the entity is present. The syntax is as follows:
Code Snippet:
<!DOCTYPE MusicCollection [
<!ENTITY R "Rock">
<!ENTITY S "Soft">
<!ENTITY RA "Rap">
<!ENTITY HH "Hiphop">
<!ENTITY F "Folk">
]>
Parameter Entity
These types of entities are used only in the DTD. These type of entities are declared in DTD. Both
internal and external parameter entities should not be used in the content of the XML document
as the processor does not recognise them. A well-formed parameter entity is similar to general
entity, except that it will include the % specifier. The reference is also similar to the general entity
reference.
References to these entities are made by using percent-sign (%) and semicolon (;) as delimiters.
Concepts
The following code demonstrates an example of parameter entity.
Code Snippet:
A well-formed parameter entity will look like a general entity, except that it will include the "%"
specifier.
A doctype declaration is declared to indicate what DTD the document adheres to. It can be declared
either in the XML document or can reference an the external document.
Syntax:
where,
[Internal DTD subset] are those declarations that are in the document.
Code Snippet:
DTD File:
1.4.9 Attributes
Concepts
Attributes are part of the elements. They provide information about the element and are embedded in
the element start-tag. An attribute consists of an attribute name and an attribute value. The name always
precedes its value, which are separated by an equal sign. The attribute value is enclosed in the quotes
to delimit multiple attributes in the same element. An attribute can be of CDATA, ENTITY, ENUMERATION,
ID, IDREF, NMTOKEN or NOTATION.
An enumerated attribute value is used when the attribute values are to be one of a fixed set of legal
values. The attribute of identifier type (ID) should be unique. It is used to search a particular instance
of an element. Each element can only have one attribute of type ID. IDREF is also an identifier type
and it should only point to one element. IDREF attributes can be used to refer to an element from
other elements. An attribute of type NMTOKEN allows any combination of name token characters. The
characters can be letters, numbers, periods, dashes, colons or underscores. An NMTOKENS type attribute
allows multiple values but separated by white space. A NOTATION type attribute must refer to a notation
declared elsewhere in the DTD. A declaration can also be an example for a list of notations.
Syntax:
Code Snippet:
Unlike child elements, they do not contain multiple values and do not describe structures.
Knowledge Check 4
Concepts
1. Which of the following statements are true in the case of comments and processing instructions in
XML?
2. Which of the following statements are valid for character data in XML?
Module Summary
Concepts
In this module, Introduction to XML, you learnt about:
Introduction to XML
XML was developed to overcome the drawbacks of earlier markup languages. XML consists
of set of rules that describe the content to be displayed in the document. XML markup
contains the content in the information containers called as elements.
Exploring XML
XML document is divided into two parts namely document prolog and root element. An XML
editor creates the XML document and a parser validates the document.
XML document is divided into XML Version Declaration, DTD and the document instance in
which the markup defines the content. The XML markup is again categorized into structural,
semantic and stylistic. The output of the XML document is displayed in the browser if it is
well formed.
XML Syntax
Comments are used in the document to give information about the line or block of code. The
content in XML document is divided into mark up and character data. The entities in XML are
divided into general entities and parameter entities. A DTD can be declared either internally
or externally.
Namespaces
Concepts
Module Overview
Welcome to the module, Namespaces. This module introduces XML Namespaces and the reasons
for using Namespaces in XML documents. This module aims at giving a clear understanding of
Namespaces syntax.
XML Namespaces
XML allows developers to create their own elements and attributes for their own projects. These elements
or attributes can be shared by the developers working on similar projects all over the world.
For example, an author of an XML document includes element called <title> in a <CD> element and
another author creates an element <title> in a <Book> element. A problem will arise if the <title>
element created by two different authors, is merged into a single XML document. XML developer has to
ensure the uniqueness of the element names and attributes in a document.
When authors begin integrating the XML documents from different developers, name conflicts are
inevitable. In such a scenario, it becomes difficult for the browser to distinguish a conflicting element in a
XML document.
Consider an example where there are two occurrences of the <title> element in an XML document, one
suggesting the title of a CD whereas another suggesting the title of a book. Imagine that an application is
supposed to access this document and search for the <title> element. An XML parser will be lost if it
does not get an additional information to search for a specific title.
2.1.3 Namespaces
In XML, elements are distinguished by using namespaces. XML Namespaces provide a globally unique
name for an element or attribute so that they do not conflict one another.
A namespace is a collection of names that can be used as element names or attribute names in XML
document.
Reusability
XML Namespaces enable reuse of markup by making use of the elements and attributes that were
defined earlier.
Modularity
Reusable code modules can be written, and these can be invoked for specific elements or attributes.
Elements and attributes from different modules can be integrated into a single XML document.
Universally unique element names and attributes guarantee that such modules can be invoked for
certain elements and attributes.
Extensibility
XML Namespaces provide the XML documents with the ability to embed elements and attributes
from other vocabularies like MathML, XHTML (Extensible HyperText MarkUp Language), and so
forth.
Note: A Namespace is identified by the Uniform Resource Identifier (URI). For example, we can have all
Concepts
three elements named as 'batch'. The first referring the batch of students in Aptech Education Center,
the second a batch of products, and the third, a batch of tourists. The element batch can be identified
with a unique URI as given.
http://www.Aptech_edu.ac.batch
http://www.tea.org.batch
http://www.tourism.org.batch
Knowledge Check 1
1. Which of these statements about XML elements and XML Namespaces are true and which statements
are false?
(A) Browser has the ability distinguish duplicate element names in an XML document.
(B) XML developer has to ensure the uniqueness of the element names and attributes in a
document.
(C) A namespace is a collection of names that can be used as element names or attribute
names in XML document.
(D) In XML, elements are distinguished by using DTD.
In this last lesson, Working with Namespaces syntax, you will learn to:
Namespaces are a mechanism by which element and attribute names can be assigned to groups. They
also ensure that there is no conflict within element names. The best way to solve this problem is for every
element in a document to have a completely distinct name. Therefore, the XML Namespace prefixes are
directly attached to names as well as names of its attributes and descendants.
Using prefixes in the element names provide a means for the document authors to prevent name collisions,
as demonstrated in the following code.
Concepts
Code Snippet:
and
There is a drawback to the prefix approach of the namespaces in an XML document. The reason for
prefixing an element in a XML document is to prevent it from being duplicated. However, if the prefixes
are not unique, the original problem of duplication would still exist.
To solve this problem, each namespace prefix is added to a Uniform Resource Identifier or URI that
uniquely identifies the namespace. URI is a series of characters used to differentiate names.
To guarantee name uniqueness in any XML documents that the company creates, the documents are
associated with their namespace. The following code demonstrate a company's URI which is located at
http://www.spectrafocus.com.
Code Snippet:
Note: The namespace prefix is an abbreviation for the namespace identifier (URI). For the student
application, the prefix S or s can be chosen. The elements with the S prefix are said to have qualified
names. The part of the name after the colon is called the local name.
Concepts
The XML namespace attribute is placed in the start tag of an element and the syntax for the namespace
is given in figure 2.2.
namespacePrefix
Each namespace has a prefix that is used as a reference to the namespace. Prefixes must not
begin with xmlns or xml. A namespace prefix can be any legal XML name that does not contain a
colon. A legal XML name must begin with a letter or an underscore.
elementName
xmlns
The xmlns attribute is what notifies an XML processor that a namespace is being declared. xmlns
stands for XML Namespace.
URI
A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource.
The URI includes Uniform Resource Name (URN) and a Uniform Resource Locator (URL). URLs
contain the reference for a document or an HTML page on the Web. The URN is a universally
unique number that identifies Internet resources. Additionally, URIs are also case-sensitive, which
means that the following two namespaces are different: http://www.XMLNAMESPACES.com,
http://www.xmlnamespaces.com.
The purpose of namespaces, when used in an XML document, is to prevent the collision of
similar elements and attribute names. A namespace in XML is simply a collection of element and
attribute names identified by a URI reference. A URI reference is nothing but a string identifier.
A URI need not be valid, for example, there may not be an actual Web site with the name
http://www.xmlnamespaces.com. In particular, the URIs do not need to be valid or point to an
actual resource.
URIs need not be valid, therefore, XML namespaces treat them like strings. In particular, comparisons
are done character-by-character. According to this definition, the following URIs are not identical
Concepts
Code Snippet:
<Auc:Books xmlns:Auc="http://www.auction.com/books"
xmlns:B="http://www.books.com/HTML/1998/xml1">
...
<Auc:BookReview>
<B:Table>
...
The elements that are prefixed with Auc are associated with a namespace with name http://
www.auction.com/books, whereas those prefixed with B are associated with a namespace
whose name is http://www.books.com/HTML/1998/xml1.
Note: URIs encompasses both URLs and URNs. URNs differ from URLs in that URLs describe the
physical location of the particular resource, whereas URNs define a unique location-independent name
for a resource that maps to one or more URLs. URLs all begin with Internet service prefix such as ftp:,
http:, and so on, whereas URNs begin with urn: prefix.
Attributes belong to particular elements and they are not a part of namespace, even if the element is
within some namespace. However, if an attribute name has no prefix, it has no namespace. An attribute
without a prefix is in default namespace. If an attribute name has a prefix, its name is in the namespace
indicated by the prefix.
Syntax:
prefix:localname='value'
or
prefix:localname="value"
where,
Concepts
prefix is used as a reference to the namespace. Prefixes must not begin with xmlns or xml.
In the following code, the type attribute is associated with the book namespace since it is preceded by
the prefix Book.
Code Snippet:
Note: Attributes from a particular namespace can also be added to elements from a different namespace.
The following example demonstrates this concept.
<Catalog xmlns= "http://www.Aptech_edu.ac" xmlns:Author= "http://www.
aptechworldwide.com">
<Book Type= "Adventure">The Last Samurai</Book>
<Book Author:Type= "Fiction">Hannibal</Book>
<Book>American Dream</Book>
</Catalog>
Consider an XML document which contains the details of all books in a library. Since this document
includes a lot of markup all in the same namespace it may be inconvenient to add a prefix to each element
name. Consider another scenario where an XML document is to merge with a MathML document.
This problem can be solved by adding a default namespace to an element and to its child elements using
an xmlns attribute with no prefix.
A default namespace is used by an element and its child elements if the element does not have a
namespace prefix.
MathML Document
Concepts
Code Snippet:
<MRow>
<Mi>x</Mi>
<Mo>+</Mo>
<Mn>1</Mn>
</MRow>
Syntax:
<elementName xmlns='URL'>
where,
elementName specifies the name of the element belonging to the same namespace.
URL specifies the namespace which is reference for a document or an HTML page on the Web.
Code Snippet:
<Catalog xmlns="http://www.aptechworldwide.com">
<BookList>
<Title type = "Thriller">African Safari</Title>
<Price>$12</Price>
<ISBN>23345</ISBN>
</Booklist>
</Catalog>
A default namespace using the xmlns attribute with a URI as its value. Once this default namespace is
declared, child elements that are part of this namespace do not need a namespace prefix.
Concepts
The default namespace applies to the element on which it was defined and all descendants of that
element. If one of the descendants has another default namespace defined on it, this new namespace
definition overrides the previous one and becomes the default for that element and all its descendants as
demonstrated in the following code.
Code Snippet:
Notice that in the price element in the second book element a different namespace is provided. This
namespace applies only to the price element and overrides the namespace in the catalog element.
Some of the best practices that are used for declaring XML Namespaces are as follows:
Logical and consistent prefix names should be used for convenience while creating an XML
document.
Namespaces should be applied to a personal vocabulary, even when there is just one.
Namespaces should be used to separate or isolate elements that may otherwise seem similar.
When designing two vocabularies that have some elements in common, one namespace should
be used to hold the common items.
Namespace URI should change for every substantive change to the vocabulary, including the
addition and deletion of new elements.
If possible, one prefix should be used for one namespace throughout all XML documents in a
system.
All namespace declarations should be made in the start tag of the document element.
Knowledge Check 2
2. Which of these statements about attributes and namespaces are true and which statements are
false?
(A) Attributes belonging to a particular elements within some namespace is also a part of the
same namespace.
(B) An attribute without a prefix is in default namespace.
(C) xmlns:localname="value" is the correct syntax for including a attribute in a
namespace.
(D) <Student:Name age = "12">Kevin</Student:Name> is the correct for associating
age with the student namespace.
(E) The prefix used in an attribute is used as a reference to the namespace.
3. Which of these statements about default namespaces are true and which statements are false?
Concepts
(A) <elementName xmlns='URL'> is the correct syntax for declaring a default namespace.
(B) The descendant has the same namespace as the parent element even if it has a new
namespace definition.
(C) A default namespace is used by an element and its child elements if the element has a
namespace prefix.
(D) A default namespace applies to the element on which it was defined and all descendants of
that element.
(E) A descendant having a new namespace cannot override the namespace defined by the
parent element.
Module Summary
Concepts
XML Namespaces
Namespaces distinguish between elements and attributes with the same name from different
XML applications. It is a collection of names that can be used as element names or attribute
names in XML document. XML Namespaces provide a globally unique name for an element or
attribute to avoid name collisions.
Namespaces are declared by an xmlns attribute whose value is the URI of the namespace. If an
attribute name has no prefix, it has no namespace. A default namespace is used by an element
and its child elements if the element does not have a namespace prefix.
DTDs
Concepts
Module Overview
Welcome to the module, Document Type Definitions (DTDs). This module focuses on how to
create DTDs for XML files. In this module, topics such as DOCTYPE declarations, types of DTDs,
well-formedness, and validity of XML files, declaration of elements, attributes, and entities in a
DTD are also covered.
Declarations
In this first lesson, Document Type Definition, you will learn to:
A Document Type Definition (DTD) is a non XML document made up of element, attribute and entity
declarations. The elements, attributes and entities defined belong to the XML document(s) the DTD is
defined for.
The DTD helps XML parsers to validate the XML document. It also helps authors to set default values for
element attributes. The document's tree structure can be determined based on the DTD.
Note:
Tree Structure
Hierarchical representation of an XML document, its root element, other elements, entities, and so on.
This structure is conceptually interpreted as the document's tree structure.
XML Parsers
Concepts
An XML parser is a software program or set of programs that parses XML documents for its structure.
XML parsers are also capable of validating XML files depending on DTDs.
The fact that XML allowed its user to define his/her own tag was one of its biggest advantages. However,
it also led to a genuine problem. People working on parts of the same XML document sometimes used
similar tags for different purposes and at other times, used different tags for the same purpose. At times,
same elements possessed or exhibited different attributes. Some sort of standardization of elements and
attributes was needed.
That is how DTDs came into picture. A DTD can define all the possible combinations and sequences for
elements to be used in an XML document along with their attributes and their acceptable values.
The difference between a Document Type Definition (DTD) and a Document Type Declaration (DOCTYPE)
can be derived from table 3.1:
<!DOCTYPE name_of_root_element
SYSTEM "URL of the external DTD
subset" >
Language Type Non XML XML
Concepts
Variations Present within a DOCTYPE (Internal Declaring either an internal or external
DTD) or in an external document DTD
(External DTD)
Dependency Is useful only if declared using Is useful only if it has a DTD to define
DOCTYPE declaration
The difference between the two is clear from Table 3.1. The DOCTYPE declaration is very important for
the DTD to be functional and in the absence of a DTD, a DOCTYPE declaration becomes ineffective.
DOCTYPE declarations can declare DTDs within themselves or refer to DTDs present in external
documents. Depending on either of the two, DTDs can be termed as internal or external respectively.
The following example shows how to declare a DTD within a DOCTYPE declaration.
Example:
File: Mobile.xml
...
<!DOCTYPE Mobile [
<!ELEMENT Mobile (Company, Model, Price, Accessories)>
<!ELEMENT Company (#PCDATA)>
<!ELEMENT Model (#PCDATA)>
<!ELEMENT Price (#PCDATA)>
<!ELEMENT Accessories (#PCDATA)>
<!ATTLIST Model Type CDATA "Camera">
<!ENTITY HP "Head Phones">
<!ENTITY CH "Charger">
<!ENTITY SK "Starter's Kit">
]>
...
Additionally, the following example displays the same DTD shown in the previous example but in the form
of an external DTD.
Concepts
Example:
File: Mobile.dtd
<!ELEMENT Mobile (Company, Model, Price, Accessories)>
<!ELEMENT Company (#PCDATA)>
<!ELEMENT Model (#PCDATA)>
<!ELEMENT Price (#PCDATA)>
<!ELEMENT Accessories (#PCDATA)>
<!ATTLIST Model Type CDATA "Camera">
<!ENTITY HP "Head Phones">
<!ENTITY CH "Charger">
<!ENTITY SK "Starter's Kit">
File: Mobile.xml
...
<!DOCTYPE Mobile SYSTEM "Mobile.dtd">
...
The DTD is declared in a separate file "Mobile.dtd". The DOCTYPE declaration in the XML file refers to
it using the SYSTEM keyword.
The purpose of DTDs is to facilitate validation. This fact makes DTDs both popular and essential. However,
DTDs have limitations of their own. They are:
DTDs validate XML documents but themselves are non-XML documents. One of the biggest
advantages of XML is its extensibility. However, DTDs cannot boast of this extensibility.
DTDs can be either external or internal depending on their DOCTYPE declaration. In spite of such
provisions, every XML document can have only one DTD to adhere to. This limits the advantage
of having both internal and external DTDs.
DTDs do not follow the latest trends of being object oriented, inheritance, and so on. This puts
them behind widely used programming languages and programmer preferences.
XML documents can use multiple namespaces. To use a namespace, XML documents require the
namespace to be declared within its DTD. However, DTDs do not support multiple namespaces.
This defeats the very advantage of being able to declare multiple namespaces.
DTDs support only one datatype, the text string. This is one of its biggest disadvantages
depending on the number of applications XML is being used for today.
Concepts
Being able to define DTDs for standardizing XML documents is surely one of DTDs biggest tenets.
However, this is proving to be helpless with internal DTDs being able to override external DTDs.
Hours of efforts in creating effective DTDs could be ruined by malicious internal DTDs. Thus, the
security aspect of DTDs is very doubtful.
Knowledge Check 1
1. Which of the statements about DTDs and their purpose are true and which statements are false?
In this second lesson, Working with DTDs, you will learn to:
Element Declarations
Attribute Declarations
Entity Declarations
Each element declaration specifies the name of the element, and the content which that element can
contain. Each attribute declaration specifies the element that owns the attribute, the attribute name, its
Concepts
type and its default value (if any). Each entity declaration specifies the name of the entity and either its
value or location of its value.
These groups of element, attribute and entity declarations that form the three blocks of a DTD respectively
can be declared in any sequence.
Steps 1 to 3 deal with element declaration, steps 4 and 5 with attribute declarations and step 6 with entity
declarations. This is in clear accordance with the structure of a DTD.
Syntax:
Concepts
Code Snippet:
A Document Type Declaration declares that the XML file in which it is present adheres to a certain DTD.
The declaration also specifies the name of that DTD and either its content or location.
Placed in the XML document's prolog, a DOCTYPE declaration begins with <!DOCTYPE and ends with a
>. In between is the name of the root element, followed either by a pair of square brackets containing the
DTD itself or by the SYSTEM keyword and a URL specifying where the DTD can be found.
Without the document type declaration, a DTD is nothing but plain text.
Syntax:
Concepts
or
DOCTYPE declarations have two basic forms of syntax. Depending on the document type declaration
syntax used, DTDs can be classified as Internal or External DTDs.
Internal DTDs
Internal DTDs are characterized by the presence of the DTD in the document type declaration itself.
The document type declaration consists of the DTD name followed by the DTD enclosed in square
brackets.
External DTDs
External DTDs are characterized by the presence of the DTDs address path in the document type
declaration. The document type declaration consists of the DTDs name followed by the SYSTEM
keyword followed by the address of the DTD document.
Concepts
Figure 3.3: External DTD
Knowledge Check 2
1. Which of the statements about DTD structure and DOCTYPE declarations are true and which
statements are false?
(A) DTDs are made up of three blocks of declarations and the DOCTYPE declaration.
(B) Elements, attributes and entities can be declared in any order.
(C) DOCTYPE declarations are specified in the prolog of the XML document.
(D) Internal DTDs specify the DTD within square brackets in the declaration itself.
(E) External DTDs use the keyword URL to specify the location of the DTD.
In this third lesson, Valid XML Documents, you will learn to:
For an XML document to execute properly, it should be well-formed. A well-formed XML document
adheres to the basic XML syntax rules. The World Wide Web Consortium in its specifications, states that
XML documents with errors should not be processed by any program. The basic XML syntax rules are
as follows:
Concepts
A Valid XML document is a well-formed XML document that adheres to its DTD. The validity of an XML
document is determined by checking it against its DTD. Once it has been confirmed that the components
used in the XML document adhere to the declarations in the DTD, a well-formed XML document can be
termed as a valid XML document.
Validity of XML documents plays an important role in all XML applications. Be it creating modular parts
of the code, or data interchange, or processing of transferred data, or database access, and so forth,
validity of the XML document is a recommended feature. The following code demonstrates a valid XML
document.
Code Snippet:
Validity being a desirable trait, it is necessary to be able to validate XML documents after their creation.
Validity of XML documents can be determined by using a validating parser such as MSXML 6.0 Parser.
MSXML enables the Internet Explorer (IE) browser to validate the code. Once the code is displayed in IE,
right-click the code to display the context menu. The menu provides the option of validating the code. On
selection, IE internally validates the code against the code's DTD.
The first image of figure 3.5 displays the validation result of a valid mobile.xml file.
The second image of figure 3.5 displays the validation result after the removal of the signature element
from the document's DTD.
Knowledge Check 3
Concepts
1. Which of the following XML code snippets is valid?
<!DOCTYPE mobile [
<!ELEMENT Mobile (Company, Model, Price, Accessories)>
<!ELEMENT Company (#PCDATA)>
<!ELEMENT Model (#PCDATA)>
<!ELEMENT Accessories (#PCDATA)>
<!ATTLIST Model Type CDATA "Camera">
<!ENTITY HP SYSTEM "hp.txt">
<!ENTITY CH SYSTEM "ch.txt">
<!ENTITY SK SYSTEM "sk.txt">
]>
<Mobile>
(A) <Company> Nokia </Company>
<Model Type="Camera"> 6600 </Model>
<Price> 9999 </Price>
<Accessories> &HP;, &CH; and a &SK; </Accessories>
</Mobile>
hp.txt
Head Phones
ch.txt
Charger
sk.txt
Starter's Kit
<!DOCTYPE Mobile [
Concepts
hp.txt
Head Phones
ch.txt
Charger
sk.txt
Starter's Kit
<!DOCTYPE Mobile [
Concepts
<!ELEMENT Mobile (Company, Model, Price, Accessories)>
<!ELEMENT Company (#PCDATA)>
<!ELEMENT Model (#PCDATA)>
<!ELEMENT Price (#PCDATA)>
<!ELEMENT Accessories (#PCDATA)>
<!ATTLIST Model Type CDATA "Camera">
<!ENTITY HP SYSTEM "hp.txt">
<!ENTITY CH SYSTEM "ch.txt">
<!ENTITY SK SYSTEM "sk.txt">
]>
(C) <Mobile>
<Company> Nokia </Company>
<Model Type="Camera"> 6600 </Model>
<Price> 9999 </Price>
<Accessories> &HP;, &CH; and a &SK; </Accessories>
</Mobile>
hp.txt
Head Phones
ch.txt
Charger
sk.txt
Starter's Kit
<!DOCTYPE Mobile [
Concepts
hp.txt
Head Phones
ch.txt
Charger
sk.txt
Starter's Kit
3.4 Declarations
Concepts
In the DTD, XML elements are declared with an element declaration. An element declaration has the
following syntax:
Syntax:
where,
element-rule can be one of the following: No Content, Only Parsed Character Data. Any
Contents, Children, Only One Occurrence, Minimum One Occurrence, Zero or More Occurrences,
Zero or One Occurrence, Either/Or Content or Mixed Content.
Some of the syntax and declarations for the element-rule options are shown in table 3.2.
Other declarations and the syntax that can be given for the element-rule options are shown in table 3.3.
Concepts
Zero or One Elements with children <!ELEMENT <!ELEMENT
Occurrences names accompanied by a '?' element-name Mail (To*,
sign inside the parentheses (child-name?)> From+, Date+,
can be skipped or only Time+, Cc,
appear once in the XML Bcc, Subject+,
document. Message+,
Signature?)>
Either/Or Content Elements can have either <!ELEMENT element- <!ELEMENT Mail
one of two or more children name (child-name, (To, From,
by specifying them in (child-name|child- Date, Time,
parentheses separated by name))> (Cc|Bcc),
'|'. Subject,
Message,
Signature)>
Mixed Content Elements can be declared to <!ELEMENT element- <!ELEMENT Mail
accept mixed content, either name (type|child- (To|From|Date|T
data type or children, etc. name|)> ime|Cc|Bcc|Subj
ect|Message|Sig
nature)>
Syntax:
where,
Value Description
PCDATA Parsed character data
CDATA Character data
(en1|en2|..) Enumerated list
ID A unique id
IDREF Id of another element
IDREFS List of other ids
NMTOKEN Valid XML name
NMTOKENS List of valid XML names
ENTITY An entity
ENTITIES List of entities
NOTATION Name of a notation
xml: Predefined xml value
The attributevalue in a DTD declaration can have values as shown in table 3.5.
Value Description
value Default value
#REQUIRED Value must be included
#IMPLIED Value does not have to be included
#FIXED Value is fixed
en1|en2|... Listed enumerated values
Syntax:
#IMPLIED
#REQUIRED
#FIXED
Concepts
<!ATTLIST element-name attribute-name attribute-type #FIXED "value">
Code Snippet:
Default Value
#IMPLIED
#REQUIRED
#FIXED
An entity, in XML, is a placeholder that consists of a name and a value. It is declared once and then
repeatedly used through out the document in place of its value.
Entities can be categorized as parameter entities and general entities. Parameter entities have been
discussed earlier.
Character
Mixed Content
Unparsed
Character entities are entities that have a single character as their replacement value. Character entities
are further classified as:
Pre-defined
Numbered
Name
XML has a set of pre-defined entities to facilitate the use of characters like <, >, &, ", ', since these are
used by XML in its tags.
The Pre-defined entities and their references are shown in table 3.6.
Numbered entities are entities which use a character reference number, for a character from the Unicode
character set, in place of the character itself. These entity references have a special syntax. Instead of the
"&", "&#" is used. The reference number is used as the name, followed by a semicolon. Thus, a numbered
entity reference would look like this: õ. The numbers can also be specified in hexadecimal, if
required, using the following syntax:
Name entities are the same as Numbered entities, except that the numbers are replaced by a descriptive
name for the character.
Mixed content entities are entities that contain either text or markup language text as their replacement
value. For example, the entity test could also have "trial" or "<trial>Hi!</trial>" as its replacement value.
Concepts
The text "<trial>Hi!</trial>" will be replaced with the entity reference and will act as an element trial.
Unparsed entities are entities that have data that is not to be parsed. The replacement value might be an
image or a file or something else. The syntax for an unparsed entity is as follows:
<!DOCTYPE name [
<!ENTITY entity-name SYSTEM "entity-location" NDATA Notation Identifier>
]>
The keyword NDATA stands for notation data and notation identifier specifies the format of the file or
object.
At the time of processing, the XML parser goes through the document declarations. The parser then
scans the document for all entity references. When the parser encounters an entity reference, it replaces
the entity reference with the entity value associated with that entity. The parser then resumes parsing
from the replaced text. Entity references within the replaced text are also replaced by doing so.
Syntax:
Entity declaration:
Entity Reference:
&entity-name;
Entity references are used extensively in XML. That leads to Internal and External entity declarations, the
two basic kinds of entity declarations used in XML.
In internal entity declarations, the entity value is explicitly mentioned in the entity declaration.
Syntax:
Concepts
Code Snippet:
<!DOCTYPE Mobile [
<!ELEMENT Mobile (Company, Model, Price, Accessories)>
<!ELEMENT Company (#PCDATA)>
<!ELEMENT Model (#PCDATA)>
<!ELEMENT Price (#PCDATA)>
<!ELEMENT Accessories (#PCDATA)>
<!ATTLIST Model Type CDATA "Camera">
<!ENTITY HP "Head Phones">
<!ENTITY CH "Charger">
<!ENTITY SK "Starters Kit">
]>
<Mobile>
<Company> Nokia </Company>
<Model Type="Camera"> 6600 </Model>
<Price> 9999 </Price>
<Accessories> &HP;, &CH; and a &SK; </Accessories>
</Mobile>
In External entity declaration, a link or path to the entity value is mentioned in place of the entity
value with the help of the SYSTEM keyword. External entity declarations are in a way similar to
declaring External DTDs.
Syntax:
Code Snippet:
<!DOCTYPE Mobile [
<!ELEMENT Mobile (Company, Model, Price, Accessories)>
<!ELEMENT Company (#PCDATA)>
<!ELEMENT Model (#PCDATA)>
<!ELEMENT Price (#PCDATA)>
<!ELEMENT Accessories (#PCDATA)>
<!ATTLIST Model Type CDATA "Camera">
<!ENTITY HP SYSTEM "hp.txt">
<!ENTITY CH SYSTEM "ch.txt">
<!ENTITY SK SYSTEM "sk.txt">
]>
<Mobile>
<Company> Nokia </Company>
<Model Type="Camera"> 6600 </Model>
<Price> 9999 </Price>
<Accessories> &HP;, &CH; and a &SK; </Accessories>
</Mobile>
hp.txt
Head Phones
ch.txt
Charger
sk.txt
Starters Kit
Knowledge Check 4
Concepts
1. Can you match the element declaration descriptions with their correct syntaxes?
Description Syntax
(A) Element can contain character data but (1) <!ELEMENT element-name
to be parsed, incase it contains entity (type|child-name|)>
references.
(B) Element with a number of children (2) <!ELEMENT element-name
appearing only once in the XML (child-name+)>
document.
(C) Element can accept either data type or (3) <!ELEMENT element-name
children, and so forth. (child-name, (child-
name|child-name))>
(D) Element's children appear at least once in (4) <!ELEMENT element-name
the XML document. (#PCDATA)>
(E) Element can have either one of two or (5) <!ELEMENT element-name
more children. (child-element-name)>
2. Can you match the attribute descriptions with their correct values?
Description Value
(A) Name of a notation (1) NMTOKEN
(B) Predefined xml value (2) NOTATION
(C) id of another element (3) (en1|en2|..)
(D) valid XML name (4) xml:
(E) enumerated list (5) IDREF
<!DOCTYPE Mobile [
<!ELEMENT Mobile (Company, Model, Price, Accessories)>
<!ELEMENT Company (#PCDATA)>
<!ELEMENT Model (#PCDATA)>
<!ELEMENT Price (#PCDATA)>
<!ELEMENT Accessories (#PCDATA)>
<!ATTLIST Model Type CDATA "Camera">
(A) <!ENTITY HP "Head Phones">
<!ENTITY SK "Starters Kit">
]>
<Mobile>
<Company> Nokia </Company>
<Model Type="Camera"> 6600 </Model>
<Price> 9999 </Price>
<Accessories> &HP;, &CH; and a &SK; </Accessories>
</Mobile>
<!DOCTYPE Mobile [
<!ELEMENT Mobile (Company, Model, Price, Accessories)>
<!ELEMENT Company (#PCDATA)>
<!ELEMENT Model (#PCDATA)>
<!ELEMENT Price (#PCDATA)>
<!ELEMENT Accessories (#PCDATA)>
<!ATTLIST Model Type CDATA "Camera">
(B) <!ENTITY HP "Head Phones">
<!ENTITY CH "Charger">
<!ENTITY SK "Starters Kit">
]>
<Mobile>
<Company> Nokia </Company>
<Model Type="Camera"> 6600 </Model>
<Price> 9999 </Price>
<Accessories> HP, CH and a SK </Accessories>
</Mobile>
<!DOCTYPE Mobile [
Concepts
<!ELEMENT Mobile (Company, Model, Price, Accessories)>
<!ELEMENT Company (#PCDATA)>
<!ELEMENT Model (#PCDATA)>
<!ELEMENT Price (#PCDATA)>
<!ELEMENT Accessories (#PCDATA)>
<!ATTLIST Model Type CDATA "Camera">
(C) <!ENTITY HP "hp.txt">
<!ENTITY CH "ch.txt">
<!ENTITY SK "sk.txt">
]>
<Mobile>
<Company> Nokia </Company>
<Model Type="Camera"> 6600 </Model>
<Price> 9999 </Price>
<Accessories> &HP;, &CH; and a &SK; </accessories>
</Mobile>
<!DOCTYPE Mobile [
<!ELEMENT Mobile (Company, Model, Price, Accessories)>
<!ELEMENT Company (#PCDATA)>
<!ELEMENT Model (#PCDATA)>
<!ELEMENT Price (#PCDATA)>
<!ELEMENT Accessories (#PCDATA)>
<!ATTLIST Model Type CDATA "Camera">
(D) <!ENTITY HP "Head Phones">
<!ENTITY CH "Charger">
<!ENTITY SK "Starters Kit">
]>
<Mobile>
<Company> Nokia </Company>
<Model Type="Camera"> 6600 </Model>
<Price> 9999 </Price>
<Accessories> &HP;, &CH; and a &SK; </Accessories>
</Mobile>
Module Summary
Concepts
This lesson defines DTDs and identifies the need for DTDs.
This lesson talks about the structure of DTDs, steps to create DTDs, DOCTYPE declarations
and the type of DTDs.
This lesson talks about the well-formed valid documents and the steps to determine the
validity of XML documents.
Declarations
This lesson deals with declarations of elements, attributes, and entities in DTDs.
XML Schema
Concepts
Module Overview
Welcome to the module, XML Schema. This module focuses on exploring XML schema and
its features. The structure of an XML document with the help of schema is also discussed. This
module aims at providing a clear understanding of the different elements and data types supported
by an XML schema.
XML Schema
4.1.1 Schema
DTDs define document structure and validate XML documents, but have some limitations. Hence, an
XML-based alternative to DTDs, known as XML schema has been introduced, with an objective to
overcome the drawbacks of DTDs.
The word schema originated from a Greek word symbolizing form or shape. The dictionary meaning of
schema is: "A diagrammatic representation; an outline or a model". Initially, the word schema was only
in the reach of the philosophers till it entered the zone of computer science. In the context of software,
a schema is generally understood to be a model used to describe the structure of a database. It defines
internal structures such as tables, fields, and the relationship between them.
However, in the context of XML, as defined by the W3C, a schema is "a set of rules to constrain the
structure and articulate the information set of XML documents". A schema describes a model for a whole
Concepts
class of documents. The model describes the way in which the data is marked up, and also specifies the
possible arrangement of tags and text in a valid document. A schema might be considered as a common
vocabulary that is needed to exchange documents between different organizations.
An XML Schema defines the valid building blocks of an XML document. It can be considered as a
common vocabulary that different organizations can share to exchange documents. The XML Schema
language is referred as XML Schema Definition (XSD).
The following XML code demonstrates an entity 'BOOK'. When this document is accessed through a
browser, it will represent the details of a book.
Concepts
Code Snippet:
<Book>
<Title>Path To Paradise</Title>
<Author>David White</Author>
<Theme>Philosophy</Theme>
<Publisher>ABC Publication</Publisher>
<ISBN>11</ISBN>
<Price>$12481</Price>
<Edition>June 2000</Edition>
</Book>
The logical reasoning would compare the attributes of this 'BOOK', with the attributes of a book in general.
In other words, one's previous knowledge of what a book is, and what its attributes are, could be a kind of
schema, against which this 'BOOK' is compared. This would help to validate the attributes of the book.
The objective of an XML Schema is to define the valid structure of an XML document, similar to a DTD.
Schemas overcome the limitations of DTDs and allow Web applications to exchange XML data more
robustly, without relying on ad hoc validation tools.
XML syntax is used as the basis for creating XML schema documents. It does not require learning
a new cryptic language as is the case with DTDs.
XML schemas can be manipulated just like any other XML document.
To begin the exploration of schemas with the Hello World example, you need two files, they are:
XML File
Given XML document contains a single element, <Message>. A schema for this document has to
declare the <Message> element.
XSD File
For storing schema documents, the file is saved with ".xsd" as the extension. Schema documents
are XML documents and can have DTDs, DOCTYPE declarations.
Concepts
Figure 4.3: XSD File
Code Snippet:
Given XSD file is a schema for <Message> elements. The file is stored as message.xsd. It is an XML
document; therefore it has an XML declaration. This schema file may declare other elements too, including
ones that are not present in this XML file, but it must at least declare the <Message> element.
XML schemas allow Web applications to exchange XML data more robustly using a range of new features.
They are:
The support of XML schema for the data types and the ability to create the required datatypes has
overcome the drawbacks of DTDs. It means it is easy to define and validate valid document content
and data formats. A developer can find it simple to work with data from a database. It can also be
easy to implement the restrictions on data.
Schemas are portable and efficient as they use the same XML syntax. Hence, there is no need to
learn any new language or any editor to edit the schema files. A similar XML parser can be used to
parse the Schema files.
During data transfer, it is essential that both sender and receiver should have the same "vocabulary".
With XML Schemas, the sender can specify the data in a way that the receiver will understand.
A schema definition can be extended; hence, it is possible to reuse an existing schema to create
another schema. A developer can create his own data types derived from the standard types.
Schemas also support reference of multiple schemas in the same document.
XML checks for well-formedness of an XML document to validate the basic syntax. A document is
said to be well-formed if it has an XML declaration, unique root element, matching start and end tag,
properly nested elements, and so on. A well-formed document can still have errors. XML Schemas
can catch higher-level mistakes that arise, such as a required field of information is missing or in a
wrong format, or an element name is mis-spelled.
The support for XML Namespaces allows the programmer to validate documents that use markup
from multiple namespaces. It means that constructs can be re-used from schemas already defined
in a different namespace.
Concepts
Richer Datatypes
The Schema draft defines booleans, dates and times, URIs, time intervals, and also numeric types
like decimals, integers, bytes, longs, and many more.
Archetypes
An archetype is used to define the custom-named datatype from pre-existing data types. For
example, a 'ContactList' datatype is defined, and then two elements, 'FriendsList' and 'OfficialList'
are defined under that type.
Attribute Grouping
It is possible to have common attributes that apply to all elements, or several attributes that include
graphic or table elements. Attribute grouping allows the schema author to make this relationship
between elements explicit. Parameter entity supports grouping in DTDs, which simplifies the
process of authoring a DTD, but the information is not passed on to the processor.
Refinable Archetypes
A DTD follows a 'closed' type of content model. Content model is defined as the constraint on the
content of elements in an instance XML document. The 'closed' content model describes all, and
only those elements and attributes that may appear in the content of the element. XML Schema
allows two more possibilities:
In an 'open' content model, elements other than the required elements can also be present. The
open content model allows the inclusion of child elements and attributes within an element that are
not declared in the document's schema. DTDs only support closed content models, which require
declaring all elements and attributes in order to use them in a document. Additional elements may
be present in a 'refinable' content model, but the schema should define those additional elements.
XML inherited the concept of DTDs from Standard Generalized Markup Language (SGML), which is
an international standard for markup languages. DTDs are used to define content models, nesting of
elements in a valid order, and provide limited support to data types and attributes. The drawbacks of
using DTDs are:
DTDs do not use XML notation and therefore they are difficult to write and use.
DTDs are not extensible. For example, if there is an Address DTD to catalog friends, and one wants
to add a new section to the code for official contacts, then the entire DTD has to be rewritten.
Namespaces can be used to introduce an element type into an XML document. However, a
Namespace cannot be used to refer to an element or an entity declaration in the DTD. If a Namespace
is used, then the DTD has to be modified to include any elements taken from the Namespace.
DTDs can only express the data type of attributes in terms of explicit enumerations and a few
coarse string formats. DTDs do not have a facility to describe numbers, dates, currency values, and
so forth. Furthermore, DTDs do not have the ability to express the data type of character data in
elements. For example, a <Zip> element can be defined to contain CDATA. However, the element
cannot be constrained to just numerals when it uses a DTD.
Concepts
Code Snippet:
The following code demonstrates a sample XML File with a reference to dtd: program.xml
Code Snippet:
Additionally, examples are shown here to demonstrate how DTDs and schemas are referenced.
Code Snippet:
<?xml version="1.0"?>
<Book>
<Title> Million Seconds </Title>
<Author> Kelvin Brown </Author>
<Chapter> The plot of the story starts from here. </Chapter>
</Book>
The following code demonstrates a DTD file called "Book.dtd" that defines the elements of the
Book.xml document.
Code Snippet:
The first line of code defines the Book element to be the root element which in turn encloses three child
elements: 'Title', 'Author', and 'Chapter'. The rest of the block defines the 'Title', 'Author', and 'Chapter'
elements to be of type "#PCDATA".
The following code demonstrates that the corresponding XML Schema file called "Book.xsd" defines the
elements of the XML document Book.xml.
Code Snippet:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.booksworld.com" xmlns="http://www.booksworld.
com" elementFormDefault="qualified">
<xs:element name="Book">
<xs:complexType>
<xs:sequence>
<xs:element name="Title" type="xs:string"/>
<xs:element name="Author" type="xs:string"/>
<xs:element name="Chapter" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The Book element is a complex type because it encloses other elements. The child elements Title,
Author, Chapter are simple types because they do not contain other elements.
Concepts
The following code demonstrates that a reference to "Book.dtd" document is placed inside in an XML
document named Book.xml.
Code Snippet:
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "http://www.booksworld.com/dtd/Book.dtd">
<Book>
<Title>Million Seconds</Title>
<Author>Kelvin Brown</Author>
<Chapter>The plot of the story starts from here.</Chapter>
</Book>
The following code along with the previous code demonstrate how schema and DTD are declared and
referred in instance XML documents.
Code Snippet:
<?xml version="1.0"?>
<Book xmlns="http://www.booksworld.com" xmlns:xsi="http://www.w3.org/2001/
XMLSchema-instance" xsi:schemaLocation="http://www.booksworld.com Book.
xsd">
<Title>Million Seconds</Title>
<Author>Kelvin Brown</Author>
<Chapter>The plot of the story starts from here.</Chapter>
</Book>
Schemas overcome the limitations of DTDs and allow Web applications to exchange XML data more
robustly, without relying on ad hoc validation tools.
The Schema draft defines booleans, numbers, dates and times, URIs, integers, decimal numbers,
real numbers, and also time intervals.
Archtypes
An archetype allows to define own named datatype from pre-existing data types. For example,
one can define a 'ContactList' datatype, and then define two elements, "FriendsList" and
'OfficialList' under that type.
Attribute grouping
There can be common attributes that apply to all elements, or several attributes that include graphic
or table elements. Attribute grouping allows the schema author to make this relationship explicit.
Refinable archetypes
A DTD follows a 'closed' type of model. It describes all, and only those elements and attributes
that may appear in the content of the element. XML Schema allows two more possibilities: 'open'
and 'refinable'. In an 'open' content model, elements other than the required elements can also be
present. Additional elements may be present in a refinable content model, but the schema should
define those additional elements.
Code Snippet:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.abc.com"
xmlns="http://www.abc.com"
elementFormDefault="qualified">
<xs:element name="mail">
<xs:complexType>
<xs:sequence>
Concepts
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="header" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The following code demonstrates a sample XML File with a reference to schema: mail.xml
<?xml version="1.0"?>
<mail
xmlns="http://www.abc.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.abc.com mail.xsd">
<to>John</to>
<from>Jordan</from>
<header>Scheduler</header>
<body>3rd March Monday, 7:30 PM: board meeting!</body>
</mail>
Knowledge Check 1
1. Which of these statements about schemas are true and which statements are false?
2. Can you match the different features for DTD and schemas against their corresponding
description?
Concepts
Description Feature
(A) Allows to define own named data type from pre-existing data (1) Attribute grouping
types.
(B) Allows the schema author to make the attributes common that (2) Namespace support
apply to all elements, or several attributes that include graphic
or table elements.
(C) Describes elements which are not required to be present in the (3) Closed model
XML document.
(D) Describes only those elements and attributes that may appear (4) Archetypes
in the content of the element.
(E) Allows to validate documents that use markup from multiple (5) Open model
namespaces.
In this second lesson, Exploring XML Schemas, you will learn to:
XML Schema describes a number of built-in data types, which can be used to specify and validate the
intended data type of the content. It also allows a user to create a user-defined data type by extending the
built-in data types using facets. Hence, XML Schema recommendation defines two sorts of data types,
these are:
Built-in data types, are available to all XML Schema authors, and should be implemented by a
conforming processor.
User-derived data types, are defined in individual schema instances, and are particular to that
schema (although it is possible to import these definitions into other definitions).
In XML schema, the data types can be broadly classified into built-in and derived types.
Concepts
string
A group of characters is called a string. The string data type can contain characters, line feeds,
carriage returns, and tab characters. The string may also consist of a combination of Unicode
characters. Unicode is a universal standard to describe all possible characters of all languages with
a library of symbols with one unique number for each symbol.
Syntax:
Code Snippet:
<Customer>John Smith</Customer>
boolean
The boolean data type is used to specify a mathematical representation. Legal values for boolean
data type are true and false. True can be replaced by the numeric value 1 and false can be replaced
by the value 0.
Syntax:
Code Snippet:
<Status Disabled="true">OFF</Status>
numeric
Concepts
The data type numeric represents a numerical value. It includes numbers such as whole numbers,
and real numbers.
Syntax:
Code Snippet:
<Price>500</Price>
dateTime
It represents a particular time on a given date, written as a string. For example, "2001-05-
10T12:35:40" can be considered as a dateTime string. The date is specified in the following form
"YYYY-MM-DDThh:mm:ss":
where,
Syntax:
Concepts
<xs:element name="element_name" type="xs:dateTime"/>
Code Snippet:
<start>2001-05-10T12:35:40</start>
binary
The binary type can include graphic files, executable programs, or any other string of binary data.
Binary data types are used to express binary-formatted data of two types such as base64Binary
(Base64-encoded binary data) and hexBinary (hexadecimal-encoded binary data).
Syntax:
Code Snippet:
anyURI
A universal resource identifier (URI) represents a file name or location of the file.
Syntax:
Code Snippet:
Note: Unicode character is a character that has two bytes as its size.
Additional data types are derived from the basic built-in data types, which are called base type data
types.
The generated or derived data types, supported by the XML schema include:
integer
The base type for integer is the numeric data type. It includes both positive and negative numbers.
For example, the numbers -2, -1, 0, 1, 2 are integers. The integer data type is used to specify a
numeric value without a fractional component.
Syntax:
Code Snippet:
<Age>999</Age>
decimal
It can represent exact fractional parts such as 3.26. The basetype for decimal is the number data
type. The decimal data type is used to specify a numeric value.
Syntax:
Code Snippet:
Concepts
The decimal declaration in the schema is:
<prize>+70.7860</prize>
time
The base type is the dateTime data type. The default representation is 16:35:26. The time data
type is used to specify a time. The time is specified in the following form "hh:mm:ss" where, hh
stands for hour, mm indicates the minute and ss indicates the second.
Syntax:
Code Snippet:
<BeginAt>09:30:10.5</BeginAt>
Creating a schema using XML schema vocabulary is like creating any other XML document using a
specialized vocabulary. To understand the XML Schema vocabulary and the elements, the example
discusses an XML document that will be validated against a schema.
xs:schema xmlns:xs=http://www.w3.org/2001/XMLSchema
Every XML Schema starts with the root element <schema>. The code indicates that that the elements
and data types used in the schema are derived from the "http://www.w3.org/2001/XMLSchema"
namespace and prefixed with xs.
targetNamespace=http://www.abc.com
It specifies that the elements defined in an XML document that refers this schema, come from the
"http://www.abc.com" namespace.
xmlns=http://www.abc.com
elementFormDefault="qualified"
Concepts
It indicates that elements used by the XML instance document which were declared in this schema needs
to be qualified by the namespace.
xmlns="http://www.abc.com"
It indicates the default namespace declaration. This declaration informs the schema-validator that
all the elements used in this XML document are declared in the default ("http://www.abc.com")
namespace.
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.abc.com mail.xsd">
This schemaLocation attribute has two values. The first value identifies the namespace. The second
value is the location of the XML schema where it is stored.
Knowledge Check 2
Concepts
1. Can you match the xml data against their corresponding data type?
Description Features
(A) <prize disabled="true">999</prize> (1) dateTime
(B) <img src="http://www.abc.com/images/flowers.gif"/> (2) boolean
(C) <start>09:30:10.5</start> (3) decimal
(D) <start>2002-09-24</start> (4) time
(E) <prize>+999.5450</prize> (5) anyURI
2. The given is an instance of XML document referencing an XML schema. Can you arrange the XML
file in its proper order using the schema vocabulary?
(1) <heading>Scheduler</heading>
<body>3rd March Monday, 7:30 PM: board meeting!</body>
(2) <to>John</to>
<from>Jordan</from>
(3) </mail>
(4) <?xml version="1.0"?>
<mail xmlns="http://www.abc.com"
(5) xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.abc.com mail.xsd">
Concepts
A schema assigns a type to each element and attribute that it declares. Elements with complex type may
contain nested elements and have attributes. Only elements can contain complex types. Complex type
elements have four variations.
Empty elements
Empty elements optionally specify attributes types, but do not permit content as shown in the
following example.
Code Snippet:
<xs:element name="Books">
<xs:complexType>
<xs:attributename="BookCode"
type="xs:positiveInteger"/>
</xs:complexType>
</xs:element>
Only Elements
These elements can only contain elements and do not contain attributes as shown in the following
example.
Code Snippet:
<xs:element name="Books">
<xs:complexType>
<xs:sequence>
<xs:element name="ISBN" type="xs:string"/>
<xs:element name="Price" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Only Text
Concepts
These elements can only contain text and optionally may or may not have attributes as shown in
the following example.
Code Snippet:
<xs:complexType name="Books">
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="BookCode" type="xs: positiveInteger"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
Mixed
These are elements that can contain text content as well as sub-elements within the element as
shown in the following example. They may or may not have attributes.
Code Snippet:
<xs:element name="Books">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="BookName" type="xs:string"/>
<xs:element name="ISBN" type="xs:positiveInteger"/>
<xs:element name="Price" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Concepts
A complex element can be defined in two different ways. The following codes define the properties of
complex element.
Code Snippet:
<xs:element name="Student">
<xs:complexType>
<xs:sequence>
<xs:element name="FirstName" type="xs:string"/>
<xs:element name="MiddleName" type="xs:string"/>
<xs:element name="LastName" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
The element Student can be declared by directly mentioning it in the schema. The complex type
mentions that the XML document contains nested XML elements. The sequence element indicates
that the child elements FirstName, MiddleName and LastName appear in the same order as
they are declared.
Code Snippet:
The Student element can have a type such as PersonInfo that refers to the name of the complex
type. Several elements can reuse this complex type by referring to the name PersonInfo in their
complex type declarations.
When working with DTDs, we used the markers *, ?, and + to indicate the number of times a particular child
element could be used as content for an element. Similarly, XML schema allows specifying a minimum
and maximum number of times an element can occur. In schemas, both elements and attributes use the
following attributes:
minOccurs
minOccurs specify the minimum number of occurrences of the element in an XML document.
The default value for the minOccurs attribute is 1. If an element has a minOccurs value of 0, it
is optional. An attribute is optional, if the minOccurs is 0. If minOccurs is set to 1, the attribute is
required.
maxOccurs
maxOccurs specify the maximum number of occurrences of the element in an XML document.
The default value for the maxOccurs attribute is 1. If its value is kept unbounded, it means that the
element can appear unlimited number of times. The maxOccurs attribute defaults to 1 unless it is
specified.
The following code demonstrates the use of minOccurs and maxOccurs attributes.
Code Snippet:
<xs:element name= "Books">
<xs:complexType>
<xs:sequence>
<xs:element name="ISBN" type="xs:string"/>
<xs:element name="Quantity" type="xs:string"
maxOccurs="100" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
The example demonstrates that the Quantity element can occur a minimum of zero times and a
maximum of hundred times in the Books element.
The relationship between the minOccurs and maxOccurs attributes is displayed in table 4.1.
Concepts
minOccur MaxOccur Number of times an element can occur
0 1 0 or 1
1 1 1
0 * Infinite
1 * At least once
>0 * At least minOccurs times
>maxOccurs >0 0
Any value <minOccurs 0
A complex type can mention element content. The Element content can contain only elements. There
can be instances wherein the contained elements can also have child elements.
Code Snippet:
Books.xml
<?xml version="1.0"?>
<Books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation= "Books.xsd">
<Title>A cup of tea</Title>
<Author>
<Name>Dennis Compton</Name>
</Author>
<Author>
<Name>George Ford</Name>
</Author>
<Publisher>
<Name>Orange</Name>
</Publisher>
</Books>
Books.xsd
Concepts
<?xml version="1.0"?>
<xs:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xs:element name= "Books" type= "BookType">
<xs:complexType name= "AuthorType">
<xs:sequence>
<xs:element name= "Name" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name= "PublisherType">
<xs:sequence>
<xs:element name= "Name" type= "xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name= "BookType">
<xs:sequence>
<xs:element name= "Title" type= "xs:string"/>
<xs:element name= "Author" type="ComposerType"
maxOccurs= "unbounded"/>
<xs:element name= "Publisher" type="PublisherType"
minOccurs="0" maxOccurs= "unbounded"/>
In the XML document the Author and the Publisher elements each contain Name elements. So built-in
data types like xs:string cannot be used, instead AuthorName and PublisherName can be defined
using top level xs:complexType elements.
A complex type can specify its content as a mixed content. Mixed content can contain text mixed with
elements. The order and the number of elements that appears in the mixed content can also be specified
in the schema. This type of content may or may not have attributes.
The mixed content is declared in exactly the same way, the declaration of element content is done. The
only add-on to the declaration is, it takes a mixed attribute set to the true value.
Concepts
Code Snippet:
Book.xml
<Books>
Apocalypse written by<Author>Mary Jane</Author>
is of Genre<Category>Fiction</Type>.
</Books>
Book.xsd
<xs:element name="Books">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="Author" type="xs:string"/>
<xs:element name="Category" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
The XML Schema Language provides three grouping constructs that specify whether and how ordering
of individual elements is important:
xs:all
This grouping construct requires that each element in the group must occur at most once, but that
order is not important. The only caution is that in this type of grouping the minOccurs attribute
can be 0 or 1 and the maxOccurs attribute has to be 1. The following code demonstrates this
concept.
Code Snippet:
xs:choice
The choice element is the opposite of all elements. Instead of requiring all the elements to be
Concepts
present, it will allow only one of the choices to appear. The choice element provides an XML
representation for describing a selection from a set of element types. The choice element itself
can have minOccurs and maxOccurs attributes that establish exactly how many selections may
be made from the choice. The following code demonstrates this concept.
Code Snippet:
<xs:complexType name="AdressInfo">
<xs:group>
<xs:choice>
<xs:element name="Address" type="USAddress" />
<xs:element name="Address" type="UKAddress" />
<xs:element name="Address" type="FranceAddress" />
</xs:choice>
</xs:group>
In the code snippet, there are three child elements that are mutually exclusive. With the xs:
choice element declared, only one element among the choices can be a child element of the
parent element AddressInfo.
xs:sequence
An xs:sequence element specifies each member of the sequence to appear in the same order
in the instance document as mentioned in the xs:sequence element. The number of times each
element is allowed to appear can be controlled by the element's minOccurs and maxOccurs
attributes. The following code demonstrates this concept.
Code Snippet:
<xs:element name="Books">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string" />
<xs:element name="ISBN" type=" xs:string " />
<xs:element name="Price" type=" xs:string " />
</xs:sequence>
</xs:complexType>
</xs:element>
Knowledge Check 3
Concepts
1. Which of these statements about complex types are true and which statements are false?
(A) The order and the number of elements that appears in the mixed content cannot be specified
in the schema.
(B) If the value of maxOccurs attribute is kept unbounded, it means that the element can
appear unlimited number of times.
(C) Elements with complex type may contain nested elements and have attributes.
(D) The default value for the minOccurs attribute is 0.
(E) When a minOccurs attribute is used, there cannot be a maxOccurs attribute in the same
line.
2. Which of these statements about element and mixed content are true and which statements are
false?
(A) Mixed content means that an element whose structure is the complex type can contains
elements with attributes.
(B) Element content means a complex type element that contains only elements.
(C) The order and the number of elements appearing in the mixed content cannot be specified
in schemas.
(D) Element content cannot have attributes.
3. Which of these statements about grouping are true and which statements are false?
(A) The sequence element provides an XML representation for describing a selection from a
set of element types.
(B) The all element requires that each element in the group must occur at most once.
(C) For each element type associated with a sequence element, there must be an element in
the XML instance in the same order.
(D) The choice element cannot mention the minOccurs and maxOccurs attribute.
In this last lesson, Working with Simple Types, you will learn to:
List and describe the data types used with simple types.
A simple type is an XML element or attribute, which contains only text and no other elements or
attributes.
The simple type declarations are used to form the textual data and specify the type of data allowed within
attributes and elements.
Syntax:
In this syntax, 'XXXX' is the name of the element, 'YYYY' is the data type of the element.
The following code demonstrates that the element TotalNoOfPages can be specified as an integer
type, which is again a positive integer with three digits.
Code Snippet:
Concepts
Elements of simple type tend to describe the content and the datatype of a document, rather than its
structure.
In XML Schema, one can mention the type of data an element can contain by assigning it a particular
simple type definition. So, based upon the type of data it supports, XML schema divides the elements of
simple types into two broad categories:
There are several built-in simple types, such as integer, date, float and string that one can use without
further modifications.
A built-in simple element can contain a default value or a fixed value. A 'default' value is the value that is
assigned automatically to the element when no other value has been specified. A 'fixed' value is assigned
to an element, when there is no need to change the value for that element. Figure 4.7 depicts built-in
simple types.
Syntax:
Concepts
In this syntax, 'XXXX' is the name of the element, 'YYYY' is the data type of the element and ZZZZ is the
default value specified for the element.
Code Snippet:
The code shows the declaration of built-in simple types "AccountType" and "BalanceAmount". The fixed
value for the "AccountType" is "Savings" and the default value for "BalanceAmount" is "5000".
XML-schema supports a library of built-in datatypes. However, during the course of writing complex schema
documents, a developer may need a type of data that is not defined in the schema recommendation.
For instance, consider the declaration of an element <AngleMeasure>. It implements the available
restrictions to its content to accept non-negative numeric values, but still it accepts unwanted values
like:
<AngleMeasure>490</AngleMeasure>
As per schema declaration, "490" is a valid non-negative numeric value, but still it needs numeric type
that allows the values with a range from 0 to 360. Hence, a custom user defined datatype can be created
using the <simpleType> definition.
Syntax:
Concepts
Code Snippet:
<xs:simpleType name="AngleMeasure">
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="360"/>
</xs:restriction>
</xs:simpleType>
Code Snippet:
<xs:simpleType name="triangle">
<xs:restriction base="xsd:string">
<xs:enumeration value="isosceles"/>
<xs:enumeration value="right-angled"/>
<xs:enumeration value="equilateral"/>
</xs:restriction>
</xs:simpleType>
Elements of this type can have either the value "isosceles", or "right-angled", or
"equilateral".
4.4.5 Restrictions
Concepts
Declaration of a data type puts certain limitations on the content of an XML element or attribute. If an
XML element is of type "xs:integer" and contains a string like "Welcome", the element will not be
validated. These limitations are called restrictions, which defines allowable values for XML elements and
attributes.
Restrictions can be specified for the simpleType elements and restriction types are declared using the
<restriction> declaration. Basically, the <restriction> declaration is used to declare a derived
simpleType, which is a subset of its base simpleType. The value of the base attribute can be any existing
simpleType, or built-in XML Schema datatype.
Syntax:
In this <restriction> declaration, the base data type can be specified using the base attribute.
The following code demonstrates a simpleType "Age" is derived by specifying the base as integer type.
Code Snippet:
<xs:simpleType name="Age">
<xs:restriction base="xs:integer">
...
...
</xs:restriction>
</xs:simpleType>
4.4.6 Facets
With XML Schemas, custom restrictions can be specified on XML elements and attributes. These
restrictions are called facets.
Facets are used to restrict the set or range of values a datatype can contain. The value range defined by
the facet must be equal to or narrower than the value range of the base type.
There are 12 facet elements, declared using a common syntax. They each have a compulsory value
attribute that indicates the value for the facet. One restriction can contain more than one facet. Any values
Concepts
appearing in the instance and value spaces must conform to all the listed facets.
Facet Description
minExclusive Specifies the minimum value for the type that excludes the value provided.
minInclusive Specifies the minimum value for the type that includes the value provided.
maxExclusive Specifies the maximum value for the type that excludes the value provided.
maxInclusive Specifies the maximum value for the type that includes the value provided.
totalDigits Specifies the total number of digits in a numeric type.
fractionDigits Specifies the number of fractional digits in a numeric type.
length Specifies the number of items in a list type or the number of characters in a string
type.
minLength Specifies the minimum number of items in a list type or the minimum number of
characters in a string type.
maxLength Specifies the maximum number of items in a list type or the maximum number of
characters in a string type.
enumeration Specifies an allowable value in an enumerated list.
whiteSpace Specifies how whitespace should be treated within the type.
pattern Restricts string types.
Syntax:
The following code demonstrates that the value attribute gives the value of that facet.
Concepts
Code Snippet:
<xs:simpleType name="triangle">
<xs:restriction base="xs:string">
<xs:enumeration value="isosceles"/>
<xs:enumeration value="right-angled"/>
<xs:enumeration value="equilateral"/>
</xs:restriction>
</xs:simpleType>
Here, the facet enumeration is added to the restriction with the value attribute as either isosceles, or
right-angled, or equilateral. So, an element declared to be of type triangle must be a string with
a value of either isosceles, or right-angled, or equilateral.
4.4.7 Attributes
XML elements can contain attributes that describe elements. Within XML Schemas, attribute declarations
are similar to element declarations. To declare an attribute, <xs:attribute> element is used.
An attribute can be indicated whether it is required or optional or whether it has a default value. A default
value is automatically assigned to the attribute when no other value is specified.
The use attribute specifies whether the attribute is required or optional. Here are the different values that
can be assigned to the attributes:
Default
A default value is automatically assigned to the attribute when no other value is specified. For
example,
Fixed
Concepts
This value makes the attribute fixed. A fixed value is automatically assigned to the attribute, and
another value cannot be specified. For example,
In this code, fixed value of fiction is assigned to the attribute genre, so another value for the
attribute cannot be specified.
Optional
This value makes the attribute optional, which means that the attribute may have any value. The
default value for any an attribute is optional. For example,
In this code, the attribute genre can take any string value.
Prohibited
This value means that the attribute cannot be used. For example,
In this line of code, the element instance will not have the attribute genre.
Required
This value makes the attribute required. The attribute can have any value. For example,
In this line of code, the attribute genre has to be used in the XML element declaration.
Syntax:
where,
Attribute_datatype specifies the data type of the attribute. There are lot of built in data types
in XML schema such as string, decimal, integer, boolean, date, and time.
Concepts
Code Snippet:
In the following example, xs:attribute elements comes after xs:sequence and xs:group that
forms the body of the element. The element Name can have an optional attribute named age with type
positiveInteger.
....
<xs:complexType name= "SingerType">
<xs:sequence>
<xs:element name= "Name">
<xs:complexType>
<xs:all>
<xs:element name= "FirstName" type="xs:string"/>
<xs:element name= "LastName" type="xs:string"/>
</xs:all>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name= "age" type="xs:positiveInteger" use= "optional/>
</xs:complexType>
....
Knowledge Check 4
1. Which of the following statements about simple type elements are true and which statements are
false?
(A) A custom user defined datatype can be created using the <simpleType> definition.
(B) Elements of simple type describe the content and data type of an element.
(C) Elements of simple type constitute the structure of an XML document.
(D) A built-in simple element can contain a default value or a facet value.
(E) A default value is the value that is assigned automatically to the element when there is
no other value specified.
2. Can you match the different keywords against their corresponding description?
Concepts
Description Term
(A) Specifies the number of digits after decimal point (1) pattern
(B) Restricts string types using regular expressions (2) use
(C) Specifies an allowable value in an enumerated list (3) prohibited
(D) Specifies whether the attribute is required or optional (4) fractionDigits
(E) Specifies that the attribute cannot be used (5) enumeration
Module Summary
Concepts
In this module, XML Schema, you learnt about:
XML Schema
XML schema offers a range of data types. It supports built-in data types like string, boolean,
number, dateTime, binary and uri. Additional data types like integer, decimal, real, time,
timeperiod and user defined data types.
Elements with complex type may contain nested elements and have attributes. A complex
element can be defined by directly naming the element and by using the name and the type
attribute of the complex type. minOccurs specifies the minimum number of occurrences
of the element in an XML document. maxOccurs specifies the maximum number of
occurrences of the element in an XML document. Element content in an XML document
contains only XML elements and mixed content contains text mixed with elements. The
grouping constructs in XML schema specify the order of XML elements.
The elements of simple type describe the content and data type of the element rather
than its structure. The simple type can have built-in and user defined data types. Simple
type definition takes one of the two values, default or fixed as per the requirement. The
user-defined data type can be derived from a built in type or an existing simple type. Use
of restrictions and facets restricts its content to user prescribed values. Schema supports
usage of attributes in elements, which is declared with a simple type definition.
Style Sheets
Concepts
Module Overview
Welcome to the module, Style Sheets. This module introduces you to style sheets. It also
discusses how to use Cascading Style Sheets to format XML document. Finally, the module
explains the cascading order of style rules.
Style Sheets
Selectors in CSS
Style sheets are a set of rules that describe the appearance of data in an XML document.
XML was inspired by the problems posed by presentational markup. Presentational markup does not
describe data; it defines the appearance of data. In a document, if you had to change all proper nouns
from bold to italics, you would have to do it manually for each proper noun. Presentation markup failed to
provide same look and feel across multiple devices such as computers, Personal Digital Assistant (PDA)
devices, and cell phones.
Style sheets and XML solve these problems. XML describes data. Style sheets define the appearance of
data. However, both XML and style sheets are defined in separate files.
There are several style sheets available. However, following two are the most popular style sheets:
CSS allows you to control the appearance of data in HTML and XML documents by providing
various properties to define:
Concepts
XSL is a style sheet language used to define the appearance of data contained only in XML
documents. However, it also allows you to transform XML documents.
Cascading style sheets is a rule-based language invented in 1996 to write formatting instructions for data
contained in HTML documents.
A CSS style sheet comprises a set of rules for various elements in a document. Each rule defines how
the data enclosed in the element should be displayed.
Style sheet rules can be combined from different sources, or subsets can be created or the rules can be
overridden. The term cascading is derived from this ability to mix and match rules.
Any style or presentation changes to data can be achieved faster as changes are to be
implemented in one place.
Device independence can be achieved by defining different style sheets for different device. For
example, you can have different style sheet for desktop computers, PDAs, and cell phones.
Reduction in document code as the presentation information is stored in a different file and can be
reused.
Note: CSS is supported by most browsers available today. Some of these browsers are Netscape
(6.0 or higher), Mozilla, Opera (4.0 or higher), and Internet Explorer (5.0 or higher). However, these
browsers support only parts of CSS specification. The current CSS specification is CSS 2. CSS 3
specification is under development.
A style sheet in CSS comprises a set of style rules. These rules define how the content enclosed in an
element will be displayed. These rules are applicable to all child elements within an element. A style rule
comprises a selector, a property, and a value. A property and a value separated with a colon are referred
as property declaration. Figure 5.3 depicts the style rules.
selector
Selector is an element name of an XML document. A typical element name could be CD, Name, or
Title.
property
Property is a CSS style property that defines how the element will be rendered. Some of the CSS
properties are border, font, and color.
value
Concepts
Value is the value associated with a CSS property. One CSS property can have several values. The
various values for property font-family are the various font family names such as "times", "arial",
and "courier" to name a few.
In Cascading Style Sheets (CSS), style rules can comprise more than one selector. To include multiple
selectors or group multiple selectors, one needs to provide a comma-separated list of element names.
The following code depicts a sample XML document containing information about endangered species.
Code Snippet:
The following code demonstrates an ideal way to define style rules by displaying each element on a
separate row.
Code Snippet:
However, these three style rules can be converted to a single style rule by grouping the selectors as
demonstrated in the following code.
Code Snippet:
A single selector can have more than one property-value pairs associated with it. For example, figure 5.4
shows a CD element having two property declarations one to set the font family to sans-serif, and other
to set the color of text to black. Notice the property-value pairs are separated by a semi-colon.
Similarly, a collection of one or more property-value pairs can be associated with more than one selector.
For example, figure 5.4 shows two property declarations assigned to three elements namely CD, Title,
and Name.
In CSS, the style rules are written in a file with the extension .css. This file is associated with an XML
document using a style sheet processing instruction. A few points to note about style sheet processing
instruction are:
It should appear in the prolog section of an XML document, that is, it should appear before any tag
of an element.
One XML document can have more than one style sheet processing instructions, each linked to
one .css file.
Syntax:
where,
url is the URL of a .css file; the .css file can on a local system or anywhere on the Internet.
Concepts
type="text/css" is optional; however if a browser does not support CSS, it informs the browser
that it does not have to download a .css file.
Code Snippet:
Knowledge Check 1
1. Which of the following statements about style sheets are true and which are false?
(A) Cascading Style Sheets derived the term cascade from the ability to mix and match rules
from different sources.
(B) Cascading Style Sheets lack support to define spacing between data.
(C) A CSS style sheet is associated with an XML document using the processing instruction
xml-stylesheet.
(D) Style sheets allow you to mix presentation markup with data.
(E) Style sheets contain one or more rules about the appearance of data.
Describe ID selectors.
Simple selector comprises an element name followed by one or more property declarations. Same
property declarations can be assigned to multiple elements by separating element names with a comma.
Simple selectors match every occurrence of the element in a document.
Code Snippet:
/* Simple selector */
CD { color: black }
/* Single element, multiple property declarations */
CD { color: white; background-color: blue }
/* Multiple elements, multiple property declarations */
CD, Name, Title { color: white; background-color: blue }
A universal selector comprises an asterisk followed by property declarations. It is used when you want
to assign the same style rules to all the elements in a document. A universal selector matches all the
elements in a document. The following code displays the content of all elements in a document in blue.
Code Snippet:
* { color : blue }
5.2.3 ID Selector
An ID selector comprises a hash (#) symbol, immediately followed by an attribute's value followed by
property declarations. It is used to define styles for unique elements in a document. For example, if you
want the data of a unique element to be in a different style, you would define an ID selector for it. Unique
element is one which has one of its attributes named as id as shown in figure 5.5.
Syntax:
Concepts
#attribute_value { property_declarations }
Code Snippet:
Displays the content of an element in blue if its id attribute's value equals 1001.
ID selectors are used to emphasize the data contained in unique elements in an XML document. However,
not all browsers support ID selectors. A browser has to read the document type definition (DTD) to
identify which attributes have an ID type. Browsers such as Safari, Mozilla, and Netscape do not read
external DTD subsets. Opera lacks the ability to read internal DTDs as well. Hence, these browsers may
not apply the style rules involving ID selectors. Internet Explorer does support ID selectors as it reads
external DTDs.
Knowledge Check 2
1. Which of the following statements about selectors are true and which are false?
In this third lesson, Properties and Values, you will learn to:
The CSS provides properties to set the foreground and background color of text. CSS uses color name,
red-green-blue (RGB) values, RGB percentages and hexadecimal values to specify color values. The
various ways in which color values are specified is shown in table 5.1.
The CSS specification provides the properties color and background-color to set the foreground
and background color of text enclosed in elements.
where,
color
colorValue
Concepts
colorValue can take up any value from the CSS color table.
background-color
Figure 5.7 shows the code for style rules defined in Colors.css file.
where,
Causes the text enclosed in Cars element to be displayed in white color with a background color
of blue.
The CSS specification defines several font properties to set the font family, font size, font style such as
bold, italics, and so forth. Some of these properties are listed in table 5.2.
The font-family property is used to specify the name of the font family to be applied to an element.
where,
font-family
font-family name(s)
Comma separated list of font-family names such as serif, san-serif, monospace, cursive, and
fantasy. The list should start with the most specific font in which you want to display the data and
end with the most generic font.
Figure 5.11 shows the code for style rules stored in FontFamily.css file.
Concepts
Figure 5.11: XML File
The font-size property is used to specify the size of font used to display element data.
where,
Concepts
font-size
Figure 5.15 shows the code for style rules defined in FontSize.css file.
where,
All the text enclosed in Cars element and its child elements will be displayed with medium font
size.
The text enclosed in the element Cars will be displayed in either arial, times or serif font. The rule
becomes applicable to all the elements enclosed in Cars element. If the system does not support arial
font, then times will be selected; if times is not supported then serif will be selected.
Concepts
Figure 5.17: Output of Using font-size Property
CSS provides two properties namely font-style and font-weight to add emphasis or meaning to
parts of data.
Figure 5.18 shows the syntax for font style and weight properties.
where,
font-style
font-weight
Figure 5.19 shows the code for style rules defined in FontStyle.css file.
Concepts
where,
where,
Concepts
BMW
Liverpool
Every element in an XML document is displayed in its own box. CSS provides four properties namely
margin-left, margin-right, margin-top and margin-bottom to insert space around the
element's box.
where,
The various margin properties to set left, right, top and bottom margins.
marginValue
The value to be assigned to one of the margin properties. This value can be a fixed value or a
percentage.
Figure 5.23 shows the code for style rules defined in Margin.css file.
Concepts
where,
Inserts a space of 20 pixels to the left and a space of 50 pixels to the right of text enclosed in
element Manufacturer.
Concepts
Figure 5.25: Output of Using Margins
Borders are rectangular outlines surrounding an element's box. CSS provides properties to create dotted,
solid and groove borders to name a few.
where,
border
border_width
Specifies the thickness of the border. Possible values are thin, medium and thick.
border_style
Specifies the style of the border. Possible values are solid, dashed, dotted, groove, ridge, double,
inset, outset.
border_color
Specifies the color of the border. All values that are applicable to CSS color property are allowed.
Figure 5.27 shows the code for style rules defined in Border.css file.
Concepts
where,
Displays a thick and dashed magenta border around the content of Manufacturer element.
Displays a thick and solid olive border around the content of Model element.
Displays a thick and groove aqua border around the content of Color element.
Displays a thick and inset gray border around the content of Price element.
Concepts
Figure 5.29: Output of Using Borders
where,
BMW
M3
Metallic Silver
40,000
The border property surrounds the text in an element with an outline. To insert space between the border
and the text of an element, CSS provides the padding property.
where,
padding
padding_width
Concepts
Composite value that can have maximum four values in the following order: top, right, bottom, and
left. These values are followed by length unit designators. However, default is pixel unit.
Figure 5.31 shows the code for style rules defined in Padding.css file.
where,
Manufacturer { padding: 2 }
Inserts padding of 2 pixels between the four borders and text of Manufacturer element. The four
borders applicable are top, right, bottom, and left.
Model { padding: 2 5 }
Inserts padding between the borders and text of Model element. The value 2 is applied to top and
bottom borders and 5 is applied to left and right borders.
Color { padding: 2 5 8 }
Concepts
Inserts padding between the borders and text of Color element. The value 2 is applied to top border,
5 to left and right borders, and value 8 to bottom border.
Price { padding: 2 5 8 10 }
Inserts padding between the borders and text of Price element. The value 2 is applied to top border,
5 to right border, 8 to bottom border, and 10 to left border.
The values assigned to CSS properties are expressed in length units. Table 5.3 describes these units.
Every element's text is placed in a box of its own. Table 5.4 lists the CSS positioning properties to position
the text inside the box. Note that the properties top, left, bottom, and right are used only if value of position
property is not static.
Figure 5.34 shows the code for style rules defined in Position.css file.
Concepts
Figure 5.35: Position.css File
where,
Positions the text of Location element relative to the previous element. However, inside the box, the
content is placed at 20 pixels from top and 20 pixels from left.
Positions the text of Price element at an absolute location of 40 pixels from the top and 20 pixels
from the left.
where,
40,000
Liverpool
In HTML, if you wanted the text to appear as new paragraph, you would use the <P> tag. The same can
be achieved in XML by using CSS display property.
where,
display
none
inline
Displays the element text as inline. This is the default value if no value is specified.
block
Figure 5.38 shows the code for style rules defined in Display.css.
Concepts
Figure 5.38: XML File
where,
Inserts a new line before and after the text of element Price.
The display:block property renders the text of an element in a separate block. Inside this block,
you can align and indent the text using the CSS properties text-align and text-indent properties
respectively.
Figure 5.41 shows the syntax for text alignment and indentation.
where,
text-align
alignment_value
Can be one of the following: left (default), right, center and justify.
text-indent
value
Concepts
Floating point value followed by absolute units designators or relative units designators; or an
integer value followed by percentage (%) symbol.
Figure 5.42 shows the code for style rules defined in Align.css.
where,
Inserts a new line before and after the text of element Price and displays the text in a separate
block.
Price { text-indent: 20 }
where,
40,000
The text in element Price is display on a separate row and left indented at 20 pixels.
Knowledge Check 3
Description Property
(A) To display an element's data in italics (1) font-family
(B) To display an element's data in bold (2) font-size
(C) To display an element's data in a small font (3) font-style
(D) To display an element's data in Times New Roman (4) font-weight
(E) To display an element's data a big font (5) font-size: small
2. Can you write the style rules to display the data "XML by Example" in the format shown in the following
figure?
Note: In the image, display type is block, background color is blue, color is white, border is
Concepts
medium solid magenta, text indent is 20.
Description Property
(A) To insert space around an element (1) text-align
(B) To insert space between the text and border of element's box (2) border
(C) To display an outline around the element's data (3) padding
(D) To place element's data at the specified location (4) position
(E) To place element's data in the center (5) margin
In this last lesson, Inheritance and Cascades in CSS, you will learn to:
Explain inheritance.
There are several ways in which style sheets can be defined. For example, one document can have
more than one style sheet defined for it. A browser has its own style sheet. In such cases, it is possible
that more than one style rule may exist for an element. Hence, the World Wide Web Consortium (W3C)
defines the following rules to determine what style to apply to an element. The sorting of style rules
begins with rule number 1. If the style rule matches rule number 1, then the search is over; otherwise the
search continues with rule number 2 and so on.
1. Find all property declarations for an element in question. Apply the style rules if the element name
matches the element in the selector. If there is no style rule defined for an element, the element
inherits the style rules defined for the parent element. However, if the parent element does not have
any style rules defined, then the element is rendered with default values.
2. Style rules declared as important are considered next. A style rule can be declared important in the
following manner:
Important property declarations have a higher precedence over normal property declarations.
Note: Style rules defined as important are said to have higher weight.
Concepts
3. Next, the origin of style sheet is determined. A style sheet can have following sources:
yy Author: The author of the XML document can define a style sheet in an external document
to format the XML document.
yy User/Reader: The end-user viewing the XML document can specify his/her personal style
sheet to be used to format the XML document.
yy User-agent: The browser is referred to as user-agent. A browser has its own default style
sheet.
The style rules defined in the author's style sheet override the style rules defined in the user's style
sheet. The author's and the user's style sheet both override the user-agent's style sheet.
4. Next, the specificity of a selector is determined in that a more specific selector will override the
general selector. The specificity is determined by carrying out the following three activities:
5. Next, write the three numbers with no commas or spaces and in the same sequence as shown
earlier. Higher the number, higher is the specificity. Rules with higher specificity override the ones
with lower specificity. For example, following is a list of selectors sorted by specificity:
6. If two rules have the same weight, then the one specified last wins.
Concepts
Inheritance is the ability of one entity to acquire the characteristics of another entity. In CSS, the child
elements inherit the styles rules defined for parent element. However, this is applicable only if the child
has no explicit style rule defined for it. Otherwise, the style rule defined for child element overrides the
style rule defined for parent element.
Figure 5.45 shows that the text in element Name is displayed in italics. This is because there are no style
rules defined for elements Audio and Name. Hence, the style rule defined for CD is inherited by child
element Name.
Knowledge Check 4
1. Which of the following statements about cascading and inheritance are true and which are false?
Module Summary
Concepts
Style Sheets
Style Sheets are a set of rules that define the appearance of data. These rules are written in
a file with the extension .css. The .css file is associated with an XML document using the
xml-processing instruction.
Selectors in CSS
Selectors define the elements to which the styles will be applied. The various types of
selectors are simple, universal and ID selectors.
CSS provides several properties to define the appearance of data. Some of these properties
are color, background-color, position, padding, font, text- align to name a few.
In CSS, a child element inherits the styles rules applied to its ancestor element. Also, there
are several sources of style sheets, hence CSS follows W3C defined cascading order when
applying style rules to elements.
Concepts
Module Overview
Welcome to the module, XSL and XSLT. This module deals with the techniques of transforming
XML documents into XML, HTML, and Text documents using XSL style sheets. This module also
aims at providing a clear understanding of creating an XSL style sheet using the various XSL
elements.
Introduction to XSL
A style sheet is a collection of commands that tells a processor (such as a Web browser, or a document
reader) how to render the visual appearance of content in a Web page.
Cascading Style Sheet (CSS) is a style sheet technology that is used for HTML content formatting.
Extensible Style sheet Language (XSL) is developed by World Wide Web Consortium (W3C) to describe
how the XML document should be displayed. Figure 6.1 shows an example of style sheet.
Concepts
XSL is an XML-based language used to create style sheets. XSL is designed to format XML content for
display purposes and also has the ability to completely transform XML documents. XSL is a specification
from the World Wide Web Consortium (W3C). XSL Transformation Recommendation describes the
process of transforming an XML document, using a transformation engine and XSL. The XML document
and XSL style sheet are provided as input to the XML transformation engine, also known as the XSLT
processor. The output of the processor is in the form of a result tree in which the elements of the XML
document are converted into nodes having specific text values and attributes. XSLT processors use XSL
style sheets to gather instructions for transforming source XML documents to output XML documents.
Style sheets are used to change the structure of the XML document and modify the output.
Concepts
XSL Transformations (XSLT)
XSLT transforms an XML document into another XML document that can actually be understood
and displayed by a computer.
XPath is used as the navigator for XSL. XSL uses XPath to find parts of the source document that
should match a certain predefined template. When XPath finds the node, XSLT takes over and
performs a transformation, turning the source document into a result document.
An XML language for formatting XML documents. Once XPath has searched through the source
document and used XSLT to transform the source document into the result document, the document
then needs to be formatted so that the Web browser will be able to present the document with the
proper layout and structure. Simply put, XSL-FO is the part of XSL that produces the final output.
The transformation component of the XSL style sheet technology is XSLT. Its purpose is to transform XML
documents. It describes the process of transforming an XML document, using a transformation engine
and XSL. The XML document and XSL style sheet are provided as input to the XML transformation
engine, also known as the XSLT processor. The output of the processor is in the form of a result tree
in which the elements of the XML document are converted into nodes having specific text values and
attributes.
Note: You can transform an XML document into any text-based format, including HTML, plain text, or
Concepts
An XSLT processor is an application that connects an XML document with an XSLT style sheet. The
transformation of the XML document is in the form of a node tree, which can be displayed as output or
sent for further transformations.
The XML processor reads an XML document and processes it into a hierarchical tree containing nodes
for each piece of information in a document. After a document has been processed into a tree, the XSL
processor begins applying the rules of an XSL style sheet to the document tree.
The XSL processor starts with the root node in the tree and performs pattern matching in the style sheet.
These patterns are stored within constructs known as templates in XSL style sheets. The XSL processor
analyzes templates and the patterns associated with them to process different parts of the document tree.
When a match is made, the portion of the tree matching the given pattern is processed by the appropriate
style sheet template. At this point, the rules of the template are applied to the content to generate a result
tree. The result tree is itself a tree of data and the data has been transformed by the style sheet.
Note: Pattern matching is the process of using patterns to identify nodes in the tree that are to be
processed according to XSL styles.
Concepts
XSLT follows normal rules of XML syntax. It uses a standard document introduction, matching closing
tags for any opening tags that contain content, and a proper syntax for empty elements.
In XSL, the style rules are written in a file with the extension .xsl. This file is associated with an XML
document by using the statement <?xml-stylesheet href="xsl file" type="text/xsl"?>.
Here, the xml-stylesheet is the processing instruction.
Syntax:
All XSLT style sheets use the xsl:stylesheet element as the document element.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
</xsl:styleheet>
where,
The XSLT namespace must be declared at the top of the document in order to get access to the
XSLT elements, attributes and features.
Note: The <xsl:transform> element holds the same syntactic value as <xsl:stylesheet>. The
<xsl:transform> and <xsl:stylesheet> are completely synonymous and either can be used.
The xsl:stylesheet element is used more commonly than xsl:transform element.
The top level XSLT elements can occur directly inside the xsl:stylesheet element. An element
occurring as a child of an xsl:stylesheet element is called a top-level element. These elements
provide the building blocks for creating XSLT documents.
The top level elements in the XSLT syntax are listed in table 6.1. These elements can occur directly
inside the xsl:stylesheet or xsl:transform elements.
Concepts
Element Description
xsl:decimal-format Defines the default decimal format for number to text
conversion.
xsl:include Used to include one style sheet into another.
xsl:key Defines a named key to be used with the key() function for
operating on patterns and expressions.
xsl:output Defines the format of the output created by the style
sheet.
xsl:preserve-space Defines the format of the output created by the style
sheet.
Syntax:
where,
digit="character": Defines the character that is used to signify that a digit is needed in
a format pattern. The hash (#) is the default.
infinity="string": Defines the string that is used to represent the infinite value. The
default is the string, "infinity".
NaN="string": Defines the string that is used to indicate that the value is not a number. The
default is string, "NaN".
Concepts
pattern-separator="character":Define the character that is used to separate positive
and negative sub patterns in a format pattern. The default is semicolon (;).
percent="character": Defines the character that is used to represent a percent sign. The
default is the percent sign (%).
per-mille="character": Defines the character that is used to represent the per thousand
sign. The default is the Unicode per mille character (%).
zero-digit="character": Defines the character that is used to represent the digit zero.
The default is (0).
Code Snippet:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:decimal-format name="name" digit="D" />
<xsl:output method="html"/>
<xsl:template match="/">
<xsl:value-of select='format-number(45665789, "#.000")' />
<xsl:value-of select='format-number(0.3456789, "###%")' />
<xsl:value-of select='format-number(789, "D.0", "name")' />
<xsl:value-of select='format-number(123456789, "$DDD,DDD,DDD.
DD","name")' />
<xsl:value-of select="format-number(193 div 200, '###.#%')"/>
<xsl:value-of select="format-number(a div 0, '###,###.00')"/>
<xsl:value-of select="format-number(1 div 0, '###,###.00')"/>
</xsl:template>
</xsl:stylesheet>
The select statement returns the values 45665789.000, 35%, 789.0, $123,456,789, 96.5%, NaN
and Infinity respectively.
Syntax:
where,
href = "uri": A Uniform Resource Identifier address identifying the XSLT file to be
included.
The following code demonstrates how to include another style sheet file within a style sheet file.
Code Snippet:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:include href="ExampleTemplate.xsl"/>
<xsl:template match="/">
...........
..........
</xsl:template>
</xsl:stylesheet>
In this code, the ExampleTemplate.xsl style sheet file is included within the current style sheet
file.
Syntax:
where,
use="expression": Used to determine the value of the key for each node.
The following code contains the XML file and demonstrates how to use the xsl:key element.
Concepts
Code Snippet:
The following code contains the style sheet file and demonstrates how to use the xsl:key
element.
Code Snippet:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:key name="stafflist" match="Developer" use="@name"/>
<xsl:template match="/">
<xsl:for-each select="key('stafflist', 'David Blake')">
NAME: <xsl:value-of select="@name"/>
ADDRESS: <xsl:value-of select="@address"/>
PHONE: <xsl:value-of select="@phone"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
NAME: David Blake ADDRESS: B-602, East West Coast PHONE: 567-877-
9766
Syntax:
Attribute Description
cdata-section-elements Optional. A white space delimited list of elements whose text contents
should be written as CDATA sections.
doctype-public Optional. Specifies the public identifiers that go in the document type
declaration.
doctype-system Optional. Specifies the system identifiers that go in the document type
declaration.
encoding Optional. Sets the value of the encoding attribute in the output.
indent Optional. Specifies whether or not to indent the output. If set to "yes",
the XML and HTML outputs are step-indented to make them more
readable.
media-type Optional. Defines the MIME type of the output. The default is "text/
xml".
method Optional. Defines the type of output. The three permitted values are
HTML, text and XML. The default is XML. However, if the first child
element of the root node is the HTML <html> tag and there are no
preceding text nodes, then the default output type is set to HTML.
omit-xml-declaration Optional. A "yes" specifies that the XML declaration (<?xml...?>) should
be ignored in the output. The "no" specifies that the XML declaration
should be included in the output. The default is "no".
standalone Optional. Specifies whether the XSLT processor should output a
standalone declaration. Yes specifies that a standalone declaration
should occur in the output. No, the default, signifies that a standalone
declaration should occur in the output.
version Optional. Provides the W3C version number for the output format. If
the output is XML, the default version is 1.0. Or if the output type is
HTML, the default version is 4.0.
The following code demonstrates the use of xsl:output element. It shows that the output will be
an HTML document, version 4.0 and indented for readability.
Concepts
Code Snippet:
Syntax:
<xsl:preserve-space elements="names"/>
where,
elements: Specifies a white space separated list of element names for which white space
should be preserved or removed.
The following code demonstrates the use of xsl:preserve-space element and shows that the
white space is preserved for name and address elements.
Code Snippet:
<br/>
Concepts
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
XSL and CSS are two different style languages recommended by the World Wide Web Consortium
(W3C). XSL is more powerful and complex than CSS. Some of the differences between CSS and XSL
are listed in table 6.3.
CSS XSL
Style sheet language to create a style for HTML Style sheet language to create a style for XML
and XML documents documents
Determines the visual appearance of a page, Provides a means of transforming XML documents
but does not alter the structure of the source
document
Does not support decision structures and it Supports decision structures and can calculate
cannot calculate quantities or store values in quantities or store values in variables
variables
Uses its own notation Uses an XML notation
Highly effective and easy to learn for simple Designed to meet the needs of more complex
applications applications for richer style sheets
Knowledge Check 1
1. The steps to process an XSL style sheet and apply it to an XML document are given here. Can you
arrange the steps in sequence to achieve the processing?
2. Can you match the XSL elements against their corresponding description?
Concepts
Description XPath Node
(A) Used to add one style sheet to another (1) xsl:template
(B) Allow to set a variable in the xsl file (2) xsl:output
(C) Allow the style sheet to alias one namespace prefix (3) xsl:import
for another in the result tree
(D) Used to build templates (4) xsl:namespace-alias
(E) Allow style sheet authors to specify how they wish the (5) xsl:variable
result tree to be output
3. Which of the statements about CSS and XSL style sheet languages are true and which statements
are false?
In this last lesson, Working with XSL, you will learn to:
A template is the main component of a style sheet. Templates are defined with the help of rules. A
template rule is used to control the output of the XSLT processor. It defines the method by which an
XML element node is transformed into an XSL element node. A template rule consists of a pattern that
identifies the XML node and an action that selects and transforms the node.
Each template rule is represented by the xsl:template element. The xsl:template is an element
that defines an action for producing output from a source document.
Concepts
Built-in template rule for modes: Ensures that elements and roots in any mode are processed.
Built-in template rule for element and root nodes: Processes the root node and its children.
The built-in template rules for element and root nodes are as follows:
<xsl:template match="*|/">
<xsl:apply-templates/>
</xsl:template>
Built-in template rule for text and attribute nodes: Copies text and attribute nodes to the result
tree. The built-in template rules for text and attribute nodes are as follows:
<xsl:template match="text()|@*">
<xsl:value-of select="."/>
</xsl:template>
Built-in template rule for comment and processing instruction nodes: Does not perform any
function. It is applied to the comments and processing instructions in the XML document. The
built-in template rules for comment and processing instruction nodes are as follows:
<xsl:template match="comment()|processing-instruction()"/>
Built-in template rule for namespaces node: Does not perform any function. It is applied to the
namespaces node in the XML document. The built-in template rule for namespaces node is as
follows:
<xsl:template match="namespace()"/>
Note: The Built-in rules have a lower priority than the other template rules.
While traversing an XML document, template rules are activated in the order in which they match
the elements. A template can change the order of traversal, and it can also prevent particular
elements from being processed. The xsl:apply-templates element allows the user to choose
the order in which the document is to be traversed.
For example, consider an element Order having child elements as OrderNumber, ItemInfo,
and Price. The ItemInfo element has further child elements as ItemName and Quantity. The
Concepts
ItemName element comes before the Quantity element in the tree structure.
To get an output where Quantity is displayed before ItemName, the following template can be
used:
The xsl:template element is used to define a template that can be applied to a node to produce
desired output.
The match attribute in xsl:template is used to associate the template with an XML element. You
can also define a template for a whole branch of the XML document by using the match attribute (for
example, match="/" defines the whole XML document).
Syntax:
<xsl:template
match="pattern"
mode="mode"
name="name"
priority="number"
>
</xsl:template>
where,
match: Is a pattern that is used to define which nodes will have which template rules applied to
them. If this attribute is omitted there must be a name attribute.
name: Specifies a name for the template. If this attribute is omitted there must be a match
attribute.
priority: Is a real number that sets the priority of importance for a template. The higher the
number, the higher the priority.
Concepts
The syntax for the some of the match patterns are represented as follows:
The <xsl:template match ="/"> represents the root element in the XML document, <xsl:
template match = "name of the element"> represents all the elements in the XML document
that have the specified name, <xsl:template match = parent1/child> represents the child
element by specifying the exact parent element and <xsl:template match = "/ | *"> matches
the entire document.
The code in figure 6.5 demonstrates the usage of xsl:template element in style sheets.
An XSL style sheet is an XML document itself, it always begins with the XML declaration: <?xml
version="1.0" ?>.
The next element, <xsl:stylesheet>, defines that this document is an XSLT style sheet document. It
also contains the version number and XSLT namespace attributes.
The <xsl:template> element defines a template. The match="/" attribute associates the template
with the root of the XML source document.
The content inside the <xsl:template> element defines some HTML to write to the output.
The last two lines define the end of the template and the end of the style sheet.
The xsl:apply-templates element defines a set of nodes to be processed. This element, by default,
selects all child nodes of the current node being processed, and finds a matching template rule to apply
to each node in the set.
where,
select
mode
Allows the same nodes to be processed more than once. Each time the nodes are processed, they
can be displayed in a different manner.
Figure 6.7 shows the code for style rules that are defined in GEM_Stylesheet.xsl file.
Concepts
Figure 6.7: XML File
where,
match="GEMEmployees/Designer"
Represents the Designer child element by specifying the GEMEmployees parent element.
xsl:apply-templates select="Name"
xsl:apply-templates select="DOJ"
Concepts
xsl:value-of
xsl:template match="Name"
If the template is matched with Name element, the value of the Name element is displayed in green
color with font size 22 pixels.
xsl:template match="DOJ"
If the template is matched with DOJ element, the value of the DOJ element is displayed in blue
color.
The select attribute can be used to process nodes selected by an expression instead of processing all
children. The xsl:apply-templates with a select attribute can be used to choose a particular set
of children instead of all children.
select
Uses the same kind of patterns as the match attribute of the xsl:template element. If select attribute
is not present, all child element, comment, text, and processing instruction nodes are selected.
Figure 6.11 shows the code for style rules that are defined in book_stylesheet.xsl file.
Figure 6.12 depicts the style sheet for book_style sheet.xsl file.
Concepts
where,
select="Title"
select="Author"
The xsl:value-of element is used to write or display in the result tree a text string representing the
value of the element specified by the select attribute. A xsl:value-of element can only have one
node assigned to it.
where,
select
A mandatory attribute that assigns the node (by name) to the element.
disable-output-escaping
yes
Concepts
Indicates that special characters should be displayed as is (for example, a < or >).
no
Indicates that special characters should not be displayed as is (for example, a > is displayed as
>).
Figure 6.15 shows the code for style rules that are defined in person_stylesheet.xsl file.
where,
xsl:value-of select="FirstName"
xsl:value-of select="LastName"
The xsl:for-each element can be used to iterate through the XML elements of a specified node set.
It applies a template repeatedly to each node in a set.
Concepts
Figure 6.18: xsl:for-each Syntax
select="expresion"
The expression is evaluated on the current context to determine the set of nodes to iterate over.
Figure 6.19 shows the code for style rules that are defined in APTEmployees_stylesheet.xsl file.
where,
xsl:for-each select="Employee"
xsl:value-of select="Department"
Concepts
Displays the value of Department element.
xsl:value-of select="Name"
xsl:value-of select="Salary"
xsl:value-of select="Language"
</xsl:for-each>
The xsl:text element is used to add literal text to the output. This element cannot contain any other
XSL elements. It can contain only text.
disable-output-escaping
yes
no
Figure 6.23 shows the code for style rules that are defined in Orders_stylesheet.xsl file.
Concepts
Figure 6.23: XML File
where,
Concepts
xsl:for-each select="Orders/Item"
xsl:value-of select="Name"
<xsl:text>,</xsl:text>
<xsl:text>!!!!</xsl:text>
The xsl:number element can be used to determine the sequence number for the current node. It can
also be used to format a number for display in the output.
where,
Concepts
count="pattern"
Indicates what nodes are to be counted. Only nodes that match the pattern are counted.
Sequence of tokens that specifies the format to be used for each number in the list.
value="expression"
Specifies the expression to be converted to a number and output to the result tree.
Figure 6.27 shows the code for style rules that are defined in item_stylesheet.xsl file.
where,
position()
format="1."
format="I."
where,
Concepts
1.Water Bottle, I.Water Bottle
The fourth item is numbered with number 4 and roman number IV.
The xsl:if element evaluates a conditional expression against the content of the XML file. The test
attribute of xsl:if element contains a conditional expression that evaluates to a boolean value of true
or false.
where,
test=expression
The condition in the source data to test with either a true or false answer.
Figure 6.31 shows the code for style rules are that defined in Librarybooks_stylesheet.xsl file.
Concepts
Concepts
Figure 6.32: Librarybooks_stylesheet.xsl File
where,
<xsl:for-each select="Catalog/Book">
Checks if the price of the book is greater than 50. If true, Author, Title and Year are
displayed.
The xsl:choose element is used to make a decision when there are two or more possible courses
of action. The xsl:choose element is used in conjunction with xsl:when and xsl:otherwise to
express multiple conditional tests.
where,
xsl:when test="expression"
The xsl:when element is examined in the order of occurrence. If the test expression is true, the
code contained in that element is executed.
xsl:otherwise
If all the test conditions in any xsl:when element are false, then the xsl:otherwise element is
automatically selected and the code associated with that element is executed.
Figure 6.35 shows the code for style rules that are defined in Publisherbooks_stylesheet.xsl
file.
Concepts
Figure 6.35: XML File
where,
Concepts
xsl:when test="Price > 100"
Checks whether the price of the book is greater than 100. If true, the details like Author, Price
and Year are displayed with magenta as the background color.
xsl:otherwise
If all the conditions are false, this block is executed. Here, all other book details are printed in
normal background color.
The xsl:sort element in XSLT can be used to sort a group of similar elements. The sorting can be
done in various ways by using the attributes of this element.
case-order
Indicates whether the sort will have upper or lowercase letters listed first in the sort output. The default
option is to list uppercase first.
data-type
number
qname
text
order
The sort order for the strings. The default value is "ascending".
select
Expression that defines the key upon which the sort will be based. The expression is evaluated and
converted to a string that is used as the sort key.
Figure 3.69 shows the code for style rules that are defined in products_stylesheet.xsl file.
Concepts
Figure 6.39: XML File
select="UnitPrice"
order="descending"
The sorting order for UnitPrice is descending in that the higher value will be displayed first.
Knowledge Check 2
Concepts
1. Can you identify the correct code to display the following output "March 20, 2001 The west
coast of Atlanta some 150 dolphins" ?
XML File
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="stylesheet.xsl" ?>
<Article>
<Date>March 20, 2001</Date>
<Para>
The west coast of
<Place>Atlanta</Place>
some 150 dolphins
</Para>
</Article>
XML File
Concepts
XML File
Concepts
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="stylesheet.xsl" ?>
<Article>
<Date>March 20, 2001</Date>
<Para>
The west coast of
<Place>Atlanta</Place>
some 150 dolphins
</Para>
</Article>
XML File
Concepts
Stylesheet File
(D)
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="Article">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="Date">
<xsl:template match="Para">
<xsl:apply-templates/>
<xsl:apply-templates/>
</xsl:template>
</xsl:template>
</xsl:stylesheet>
2. Can you match the XSL elements against their corresponding description?
3. Can you identify the correct code to display the following output "A. David Blake18/11/1973"?
Concepts
XML File
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
<MichiganStaff>
<Faculty>
<Name>David Blake</Name>
<DOB>18/11/1973</DOB>
</Faculty>
</MichiganStaff>
XML File
Concepts
XML File
Concepts
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
<MichiganStaff>
<Faculty>
<Name>David Blake</Name>
<DOB>18/11/1973</DOB>
</Faculty>
</MichiganStaff>
XML File
Concepts
Module Summary
Concepts
In this module, XSL and XSLT, you learnt about:
Introduction to XSL
XML provides the ability to format document content. XSL provides the ability to define how
the formatted XML content is presented. An XSL Transformation applies rules to a source
tree read from an XML document to transform it into an output tree written out as an XML
document.
More on XSLT
Concepts
Module Overview
Welcome to the module, More on XSLT. This module aims at giving a clear understanding on
XPath, and identifying the various nodes of XPath. This module lists the different operators used
with XPath and describes the various XPath expressions and functions. Finally, this module
explains how to switch between styles and how to transform XML documents into HTML using
XSLT.
XPath
7.1 XPath
7.1.1 XPath
XPath can be thought of as a query language like SQL. However, rather than extracting information from
a database, it extracts information from an XML document. XPath is a language for retrieving information
from a XML document. XPath is used to navigate through elements and attributes in an XML document.
Thus, XPath allows identifying parts of an XML document.
XPath provides a common syntax as shown in figure 7.1 for features shared by XSLT and XQuery.
Concepts
XSLT
XSLT is a language for transforming XML documents into XML, HTML, or text.
XQuery
XQuery builds on XPath and is a language for extracting information from XML documents.
XPath is designed for XML documents. It provides a single syntax that you can use for queries, addressing,
and patterns. XPath is concise, simple, and powerful.
Any path that can occur in an XML document and any set of conditions for the nodes in the path
can be specified.
XPath is designed to be used in many contexts. It is applicable to providing links to nodes, for searching
repositories, and for many other applications.
Concepts
In XPath, an XML document is viewed conceptually as a tree in which each part of the document is
represented as a node as shown in figure 7.2.
Root
The XPath tree has a single root node, which contains all other nodes in the tree.
Element
Every element in a document has a corresponding element node that appears in the tree under
the root node. Within an element node appear all of the other types of nodes that correspond
to the element's content. Element nodes may have a unique identifier associated with them that is
used to reference the node with XPath.
Attribute
Concepts
Each element node has an associated set of attribute nodes; the element is the parent of each of
these attribute nodes; however, an attribute node is not a child of its parent element.
Text
Character data is grouped into text nodes. Characters inside comments, processing instructions
and attribute values do not produce text nodes. The text node has a parent node and it may be
the child node too.
Comment
There is a comment node for every comment, except for any comment that occurs within the
document type declaration. The comment node has a parent node and it may be the child node
too.
Processing instruction
There is a processing instruction node for every processing instruction, except for any
processing instruction that occurs within the document type declaration. The processing
instruction node has a parent node and it may be the child node too.
Namespace
Each element has an associated set of namespace nodes. Although the namespace node has
a parent node, the namespace node is not considered a child of its parent node because they
are not contained in a parent node, but are used to provide descriptive information about their
parent node.
Concepts
Node Type String Value Expanded Name
root Determined by concatenating the string- None.
values of all text-node descendents in
document order.
element Determined by concatenating the string- The element tag, including
values of all text-node descendents in the namespace prefix (if
document order. applicable).
attribute The normalized value of the attribute. The name of the attribute,
including the namespace
prefix (if applicable).
text The character data contained in the text None.
node.
comment The content of the comment (not None.
including <!-- and -->).
processing instruction The part of the processing instruction that The target of the processing
follows the target and any whitespace. instruction.
namespace The URI of the namespace. The namespace prefix.
An XPath query operates on a well-formed XML document after it has been parsed into a tree structure.
Figure 7.3 depicts a simple XML document along with its generated XPath tree.
Concepts
An XPath expression returns a node set, a boolean, a string, or a number. XPath provides basic floating
point arithmetic operators and some comparison and boolean operators.
The XPath expressions are constructed using the operators and special characters as shown in
table 7.2.
Operator Description
/ Child operator; selects immediate children of the left-side collection
// Recursive descent; searches for the specified element at any depth
. Indicates the current context
.. The parent of the current context node
* Wildcard; selects all elements regardless of the element name
@ Attribute; prefix for an attribute name
: Namespace separator; separates the namespace prefix from the element or attribute
name
Note: In floating point operators, instead of / and % the keywords div and mod are used respectively.
Table 7.3 shows few examples along with their description that use XPath operators in an expression.
Expression Refers to
Author/FirstName All <FirstName> elements within an <Author> element of the current context
node
BookStore//Title All <Title> elements one or more levels deep in the <BookStore> element
BookStore/*/ All <Title> elements that are grandchildren of <BookStore> elements
Title
BookStore//Book/ All <Work> elements anywhere inside <Excerpt> children of <Book> elements,
Excerpt//Work anywhere inside the <BookStore> element
.//Title All <Title> elements one or more levels deep in the current context
Additionally, a list of the operators that can be used in XPath expressions is given in table 7.4.
Concepts
Concepts
XPath is used in the creation of the patterns. The match attribute of the xsl:template element supports
a complex syntax that allows to express exactly which nodes to be matched. The select attribute of
xsl:apply-templates, xsl:value-of, xsl:for-each, xsl:copy-of, and xsl:sort supports
an even more powerful superset of this syntax that allows to express exactly which nodes to selected and
which nodes not to be selected.
Matching by name
The source element is simply identified by its name, using the match attribute. The value given to
the match attribute is called the pattern. The following code demonstrate the example.
Code Snippet:
Matching by ancestry
As in CSS, a match can be made using the element's ancestry. The following tag will match any 'EM'
element that has 'P' as an ancestor.
Code Snippet:
The most basic pattern contains a single element name which matches all elements with that
name. The following code demonstrate the example. This template matches Product elements
and marks their Product_ID children bold.
Code Snippet:
<xsl:template match="Product">
<xsl:value-of select="Product_ID"/>
</xsl:template>
To enable all the descendant nodes to inherit the properties on the root of document, use a single
forward slash to represent the root. The following code demonstrate the example.
Code Snippet:
Matching by attribute
Syntax:
This syntax uses square brackets to hold the attribute name and value.
Code Snippet:
<xsl:template match="Product">
<xsl:apply-templates select="@Units"/>
</xsl:template>
The given example applies the templates to the non-existent Units attributes of Product elements.
Knowledge Check 1
Concepts
1. Which of these statements about XPath are true and which of these are false?
(A) XPath provides multiple syntax that can be used for queries, addressing and patterns.
(B) XPath can be thought of as a query language like SQL.
(C) In XPath, the structure of an XML document is viewed conceptually as a pyramid.
(D) XPath provides a common syntax for features shared by XSLT and XQuery.
(E) XPath is used to navigate through elements and attributes in an XML document.
2. Can you match the XPath nodes against their corresponding description?
3. Can you match the different types of matching against their corresponding description?
In this second lesson, XPath Expressions and Functions, you will learn to:
XPath Expressions are statements that can extract useful information from the XPath tree. Instead of just
finding nodes, one can count them, add up numeric values, compare strings, and more. They are much
like statements in a functional programming language. Every XPath expression evaluates to a single
value.
Node-set
A node-set is an unordered group of nodes from the input document that match an expression's
criteria.
Boolean
A boolean has one of two values: true or false. XSLT allows any kind of data to be transformed
into a boolean. This is often done implicitly when a string or a number or a node-set is used
where a boolean is expected.
Number
XPath numbers are numeric values useful for counting nodes and performing simple arithmetic.
The numbers like 43 or 7000 that look like integers are stored as doubles. Non-number values,
such as strings and booleans, are converted to numbers automatically as necessary.
String
Concepts
A String is a sequence of zero or more Unicode characters. Other data types can be converted
to strings using the string() function.
Note: The XPath expression syntax includes literal forms for strings and numbers as well as operators
and functions for manipulating all four XPath data types.
XPath defines various functions required for XPath 2.0, XQuery 1.0 and XSLT 2.0. The different functions
are Accessor, AnyURI, Node, Error and Trace, Sequence, Context, Boolean, Duration/Date/
Time, String, QName and Numeric.
XML Path Language (XPath) functions can be used to refine XPath queries and enhance the programming
power and flexibility of XPath. Each function in the function library is specified using a function prototype
that provides the return type, function name, and argument type. If an argument type is followed by a
question mark, the argument is optional; otherwise, the argument is required. Function names are case-
sensitive.
where,
name()
The function returns the name of the current node or the first node in the specified node-set.
local-name()
The function returns the name of the current node or the first node in the specified node-set without
the namespace prefix.
namespace-uri()
The function returns the namespace URI of the current node or the first node in the specified
node-set.
root()
The function returns the root of the tree to which the current node or the specified node belongs.
This will usually be a document node.
Concepts
The output is shown in figure 7.8. The formatted output gets displayed as shown here.
Concepts
Figure 7.8: Output of Using Node-set Functions
The XML Path Language (XPath) syntax supports boolean functions that return true or false, and can be
used with comparison operators in filter patterns. Some of these functions are boolean, not, true and
false.
boolean(arg)
The function returns a boolean value for a number, string, or node-set. The syntax, code, and
output are shown.
Syntax:
fn:boolean(arg)
Code Snippet:
<ul>
<li><b>boolean(0)</b> = <xsl:value-of select="boolean(0)"/>
</li>
<li><b>boolean(1)</b> = <xsl:value-of select="boolean(1)"/>
</li>
<li><b>boolean(-100)</b> = <xsl:value-of select="boolean(-100)"/>
</li>
</li>
<li><b>boolean('')</b> = <xsl:value-of select="boolean('')"/>
</li>
<li><b>boolean(//book)</b> = <xsl:value-of select="boolean(//book)"/>
</li>
</ul>
Output:
boolean(0) = false
boolean(1) = true
boolean(-100) = true
boolean('hello') = true
boolean('') = false
boolean(//book) = false
not(arg)
The sense of an operation can be reversed by using the not() function. The syntax and code is
shown.
Syntax:
fn:not(arg)
Code Snippet:
This template rule selects all Product elements that are not the first child of their parents:
<xsl:template match="PRODUCT[not(position()=1)]">
<xsl:value-of select="."/>
</xsl:template>
The same template rule could be written using the not equal operator != instead:
Code Snippet:
<xsl:template match="PRODUCT[position()!=1]">
<xsl:value-of select="."/>
</xsl:template>
true()
Concepts
The true() function returns the boolean value true. The syntax, code, and output are shown.
Syntax:
fn:true()
Code Snippet:
<xsl:value-of select="true()"/>
Output:
true
false()
The false() function returns the boolean value true. The syntax, code, and output are shown.
Syntax:
fn:false()
Code Snippet:
The code snippet shows how to use true() and false() in XSL.
Output:
true
false
false
The value derived from an expression depends on some rules as shown in table 7.5.
Result tree fragment Always true, because every fragment contains at least one node, its root node.
Certain operators compare numerical values to arrive at a Boolean value. All the nodes in a node-set are
tested to determine whether any of them satisfies the comparison or not. The Comparison operators are
shown in table 7.6.
Operator Returns
expr = expr True if both expressions (string or numeric) have the same value, otherwise false.
expr != expr True if the expressions do not have the same value (string or numeric), otherwise false.
expr < expr True if the value of the first numeric expression is less than the value of the second,
otherwise false.
expr > expr True if the value of the first numeric expression is greater than the value of the second,
otherwise false.
expr <= expr True if the value of the first numeric expression is less than or equal to the value of the
second, otherwise false.
expr >= expr True if the value of the first numeric expression is greater than or equal to the value of
the second, otherwise false.
Note: To use some of the comparison operators inside an XML document such as an XSLT style sheet
or a schema, one must use character references < and > instead of < and >.
The different functions that return Boolean functions are shown in table 7.7.
Function Returns
expr and expr True if both Boolean expressions are true, otherwise false.
expr or expr True if at least one Boolean expression is true, otherwise false.
true() True.
false() False.
not(expr) Negates the value of the Boolean expression: true if the expression is
false, otherwise false.
Concepts
XPath syntax supports number functions that return strings or numbers and can be used with comparison
operators in filter patterns. The different numeric functions are number(arg), ceiling(num),
floor(num) and round(num).
The rules for converting any expression into a numeric value are listed in table 7.8.
To manipulate numeric values, there are a variety of operators and functions as shown in table 7.9.
Function Returns
expr + expr The sum of two numeric expressions.
expr - expr The difference of the first numeric expression minus the second.
expr * expr The product of two numeric expressions.
expr div expr The first numeric expression divided by the second expression.
expr mod expr The first numeric expression modulo the second expression.
round(expr) The value of the expression rounded to the nearest integer.
sum(node-set) The sum of the values of the nodes in node-set. Unlike the other
functions in this table, this function operates over a node-set instead
of expressions.
where,
number(arg)
The function returns the numeric value of the argument. The argument could be a boolean, a string,
or a node-set.
ceiling(num)
The function returns the smallest integer that is greater than the number argument.
floor(num)
The function returns the largest integer that is not greater than the number argument.
round(num)
The following code depicts the style sheet for numeric functions.
Concepts
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="Number.xsl"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/
Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<body>
<h3>Numeric Functions</h3>
<ul>
<li>
<b>number('1548')</b>
=
<xsl:value-of select="number('1548')"/>
</li>
<li>
<b>number('-1548')</b>
=
<xsl:value-of select="number('-1548')"/>
</li>
<li>
<b>number('text')</b>
=
<xsl:value-of select="number('text')"/>
</li>
<li>
<b>number('226.38' div '1')</b>
=
<xsl:value-of select="number('226.38' div '1')"/>
</li>
</ul>
<ul>
<li>
<b>ceiling(2.5)</b>
=
<xsl:value-of select="ceiling(2.5)"/>
</li>
Concepts
<b>ceiling(-2.3)</b>
=
<xsl:value-of select="ceiling(-2.3)"/>
</li>
<li>
<b>ceiling(4)</b>
=
<xsl:value-of select="ceiling(4)"/>
</li>
</ul>
<ul>
<li>
<b>floor(2.5)</b>
=
<xsl:value-of select="floor(2.5)"/>
</li>
<li>
<b>floor(-2.3)</b>
=
<xsl:value-of select="floor(-2.3)"/>
</li>
<li>
<b>floor(4)</b>
=
<xsl:value-of select="floor(4)"/>
</li>
</ul>
<ul>
<li>
<b>round(3.6)</b>
=
<xsl:value-of select="round(3.6)"/>
</li>
<li>
<b>round(3.4)</b>
=
<xsl:value-of select="round(3.4)"/>
</li>
Concepts
<li>
<b>round(3.5)</b>
=
<xsl:value-of select="round(3.5)"/>
</li>
<li>
<b>round(-0.6)</b>
=
<xsl:value-of select="round(-0.6)"/>
</li>
<li>
<b>round(-2.5)</b>
=
<xsl:value-of select="round(-2.5)"/>
</li>
</ul>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
String functions are used to evaluate, format, and manipulate string arguments, or to convert an object to
a string. The different String functions are shown in table 7.10.
Function Returns
concat(string, string, . . .) A string that is the concatenation of the string
arguments.
format-number(number, pattern, decimal-format) A string containing the number, formatted
according to pattern. The optional decimal-
format argument points to a format declaration
which assigns special characters like the grouping
character, which separates groups of digits in large
numbers for readability.
normalize-space(string) The string with leading and trailing whitespace
removed, and all other strings of whitespace
characters replaced with single spaces.
substring(string, offset, range) A substring of the string argument, starting offset
characters from the beginning and ending range
characters from the offset.
substring-after(string, to-match) A substring of the string argument, starting at the
end of the first occurrence of the string to-match
and ending at the end of string.
substring-before(string, to-match) A substring of the string argument, starting at the
beginning of string and ending at the beginning of
the first occurrence of the string to-match.
translate(string, characters-to-match, characters- The string with all characters in the string
replace-with) characters-to-match replaced with their
counterpart characters in the string characters-
replace-with.
Some functions operate on strings and return numeric or Boolean values, are listed in table 7.11.
Function Returns
contains(string, sub) True if the given substring sub occurs within the string,
otherwise false.
starts-with(string, sub) True if the string begins with the substring sub, otherwise
false.
string-length(string) The number of characters inside the string.
Concepts
Figure 7.11: String Functions
where,
string(arg)
The function returns the string value of the argument. The argument could be a number, boolean,
or node-set. For example: string(314) returns "314".
translate()
The function returns the first argument string with occurrences of characters in the second argument
string replaced by the character at the corresponding position in the third argument string. For
example: translate("bar","abc","ABC") returns Bar.
concat()
The function returns the concatenation of the strings. For example: concat('XPath ','is
','FUN!') returns 'XPath is FUN!'.
substring()
The function returns the substring from the start position to the specified length. Index of the first
character is 1. For example: substring('Beatles',1,4) returns 'Beat'.
Concepts
The only allowed operation in a result tree fragment is on a string. The operation on the string may involve
first converting the string to a number or a boolean. Result tree fragment is an additional data type other
than four basic XPath data types (such as, string, number, boolean, node-set).
A result tree fragment represents a fragment of the result tree. In particular, it is not permitted to use the
/, //, and [] XPath operators on Result tree fragments.
Knowledge Check 2
1. Which of these statements about XPath expressions are true and which of these are false?
(A) XSLT allows any kind of data to be transformed into a boolean value.
(B) A node-set is an unordered group of nodes from the input document.
(C) A string is a sequence of zero or more Unicode characters.
(D) The numbers like 43 or 7000 that look like integers are stored as float.
(E) A string is a sequence of one or more Unicode characters.
2. Which of these statements about XPath functions are true and which of these are false?
(A) The local-name() function returns the name of the current node or the first node in the
specified node set without the namespace prefix.
(B) The floor(num) function returns the largest integer that is not greater than the number
argument.
(C) The only allowed operation in a result tree fragment is on a number.
(D) In a substring() function, the index of the first character is 0.
(E) The translate() function returns the first argument string with occurrences of characters
in the second argument string replaced by the character at the corresponding position in the
third argument string.
Concepts
In this last lesson, Working with different styles, you will learn to:
Transformation is one of the most important and useful techniques for working with XML. XML can be
transformed by changing its structure, its markup, and perhaps its content into another form. The most
common reason to transform XML is to extend the reach of a document into new areas by converting it
into a presentational format.
Note: Transformation can be used to alter the content, such as extracting a section, or adding a table of
numbers together. It can even be used to filter an XML document to change it in very small ways, such
as inserting an attribute into a particular kind of element.
An XSLT processor takes two things as input: an XSLT style sheet to govern the transformation process
and an input document called the source tree. The output is called the result tree.
The XSLT engine begins by reading in the XSLT style sheet and caching it as a look-up table. XPath
locates the parts of XML document such as Element nodes, Attribute nodes, and Text nodes. Thus, for
each node the XSLT processes, it will look in the table for the best matching rule to apply. Starting from
the root node, the XSLT engine finds rules, executes them, and continues until there are no more nodes
in its context node set to work with. At that point, processing is complete and the XSLT engine outputs
the result document.
Note: The XSLT style sheet controls the transformation process. While it is usually called a style sheet,
it is not necessarily used to apply style. Since, XSLT is used for many other purposes, it may be better
to call it an XSLT script or transformation document.
Step 1
Step 2
Concepts
Then add the lines shown to create an XSL style sheet:
Code Snippet:
Step 3
Code Snippet:
<xsl:stylesheet>
<xsl:output method="html"/>
...
</xsl:stylesheet>
To output anything besides well-formed XML, an <xsl:output> tag should be used like the one
shown, specifying either "text" or "html". (The default value is "xml".). Figure 7.17 depicts XML
transformation.
Note: When an XML output is specified, the indent attribute can be added to produce nicely indented
XML output. The specification looks like this: <xsl:output method="xml" indent="yes"/>.
An example code of transforming XML documents into HTML using XSLT processor has been provided
to explain the process.
where,
Company
Units
A Units attribute specifies the units for the respective products melting point and boiling point.
Concepts
Figure 7.19: ProductInfo.xsl File
The output displays the transformed HTML from the XML document in the browser.
Knowledge Check 3
Concepts
1. Which of these statements about switching between styles are true and which of these are false?
(A) An XSLT processor takes three things as input such as XSLT style sheet, XML document
and Document Type Declaration.
(B) The XSLT engine begins by reading in the XSLT style sheet and caching it as a look-up
table.
(C) For each node it processes, it will look in the table for the best matching rule to apply.
(D) Starting from the root node, the XSLT engine finds rules, executes them, and continues until
there are no more nodes in its context node set to work with.
(E) XSLT can also be called as XSLT document or transformation script.
2. Can you specify the correct code snippet for transforming the XML document into HTML using
XSLT?
Concepts
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"
(C) >
<xsl:template match="/">
......
</xsl:template>
</xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"
(D) >
<xsl:template match="/">
<xsl:output method="html"/>
......
<xsl:template match="/">
</xsl:stylesheet>
Module Summary
Concepts
XPath
XPath is a notation for retrieving information from a document. XPath provides a common
syntax for features shared by Extensible Style sheet Language Transformations (XSLT)
and XQuery. XPath have seven types of node as Root, Element, Attribute, Text, Comment,
Processing instruction and Namespace. XPath is used in the creation of the patterns.
The four types of expressions in XPath are Node-sets, Booleans, Numbers and Strings. The
different functions defined for XPath are Accessor, AnyURI, Node, Error and Trace, Sequence,
Context, Boolean, Duration/Date/Time, String, QName and Numeric. A Result tree fragment is
a portion of an XML document that is not a complete node or set of nodes.
Transformation is one of the most important and useful techniques for working with XML. To
transform XML is to change its structure, its markup, and perhaps its content into another form.
Transformation can be carried out using an XSLT processor also.
1. (A) - True, (B) False, (C) True, (D) True, (E) - True
2. (A) - False, (B) - True, (C) - False, (D) - True, (E) True
Knowledge Check 2
1. (A) - True, (B) True, (C) True, (D) False, (E) - True
2. (A) True, (B) False, (C) True, (D) False, (E) - True
Answers
3. (A) True, (B) False, (C) True, (D) False, (E) False
Knowledge Check 3
1. (A)
2. (C)
Knowledge Check 4
1. (A) False, (B) False, (C) True, (D) True, (E) - False
2. (A) False, (B) False, (C) True, (D) True, (E) - False
Module 2
Knowledge Check 1
Knowledge Check 2
1. (A)
2. (A) - False, (B) - True, (C) - False, (D) - False, (E) - True
3. (A) - True, (B) - False, (C) - False, (D) - True, (E) - False
Module 3
Knowledge Check 1
1. (A) - (False), (B) - (True), (C) - (True), (D) - (True), (E) - (False)
Knowledge Check 2
1. (A) - (False), (B) - (True), (C) - (True), (D) - (True), (E) - (False)
2. (A) - Declare all the possible elements, (B) - Specify the permissible element children, if any, (C) -
Set the order in which elements must appear, (D) - Declare all the possible element attributes, (E) -
Set the attribute data types and values, (F) - Declare all the possible entities.
Knowledge Check 3
Answers
1. (C)
Knowledge Check 4
1. (A) - (3), (B) - (4), (C) - (5), (D) - (1), (E) - (2)
2. (A) - (2), (B) - (4), (C) - (5), (D) - (1), (E) - (3)
3. (D)
Module 4
Knowledge Check 1
1. (A) - True, (B) - False, (C) - False, (D) - True, (E) - True
2. (A) (4), (B) - (1), (C) - (5), (D) - (3), (E) - (2)
Knowledge Check 2
1. (A) (2), (B) - (5), (C) - (4), (D) - (1), (E) - (3)
Knowledge Check 3
1. (A) - False, (B) - True, (C) - True, (D) - False, (E) - False
Knowledge Check 4
1. (A) - False, (B) - True, (C) - True, (D) - False, (E) - True
2. (A) (4), (B) - (1), (C) - (5), (D) - (2), (E) - (3)
Module 5
Knowledge Check 1
1. (A) - True, (B) - False, (C) - True, (D) - False, (E) - True
Knowledge Check 2
Answers
1. (A) - False, (B) - True, (C) - True, (D) - True, (E) - False
Knowledge Check 3
1. (A) - (3), (B) - (4) , (C) - (5) , (D) - (1) , (E) - (2)
2. display: block;
background-color: blue;
color: white;
3. (A) - (5), (B) - (3), (C) - (2), (D) - (4) , (E) - (1)
Knowledge Check 4
1. (A) - True, (B) - True, (C) - False, (D) - True, (E) - False
Module 6
Knowledge Check 1
1. (A) - XML processor reads an XML document, (B) - XML processor creates a hierarchical tree con-
taining nodes for each piece of information, (C) - Apply the rules of an XSL style sheet to document
tree., (D) - XSL processor starts with root node in tree and performs pattern matching, (E) - Portion
of a tree matching the given pattern is processed by appropriate style sheet template.
2. (A) - (3), (B) - (5), (C) - (4), (D) - (1), (E) - (2)
3. (A) - (False), (B) - True, (C) - (True), (D) - (False), (E) - (True)
Knowledge Check 2
1. (C)
2. (A) - (5), (B) - (3), (C) - (1), (D) - (2), (E) - (4)
3. (D)
Module 7
Knowledge Check 1
1. (A) - False, (B) True, (C) False, (D) True, (E) - True
2. (A) (3), (B) - (5), (C) - (4), (D) - (1), and (E) - (2)
Answers
3. (A) (4), (B) (1), (C) (2), (D) (5), and (E) (3)
Knowledge Check 2
1. (A) - True, (B) True, (C) True, (D) False, (E) - False
2. (A) - True, (B) True, (C) False, (D) False, (E) - True
Knowledge Check 3
1. (A) - False, (B) True, (C) True, (D) True, (E) - False
2. (A)