Anda di halaman 1dari 46

Chapter 01 - Understanding Markup Languages

Saturday, July 14, 2012


8:39 PM

Today's Topics:

Homework:

Markups
Understanding markups
Open, Closed markups
Problems in markups
Specific and generalized markup
SGML

Important Points:

XML_r15 Page 1

Chapter 01 - Understanding Markup Languages


Saturday, July 14, 2012
8:40 PM

What is markup?
It refers to marking up (tagging) documents in the print and design world.
Purposes:
To modify look and formatting of text
To describe the structure and meaning of a documents for output to some medium such as printer or world
wide web
How Markup works?
Markup consists of codes or tags - these are added to text to change the look or meaning of the tagged text. For
example - <b>IDB-BISEW</b> is a HTML tagged text which is used to change the text IDB-BISEW into bold faced.
Generally a processor is used to interpret the marked up document and display or process the content.
Some common markups :
RTF - Rich Text Format
Word processors use RTF to format documents for print or display
HTML - Hyper Text Markup Language
HTML is used to format and layout document in world wide web. HTML are generally processed by
browsers.
What is a markup processor?
A markup processor interprets the meaning of the markup codes.
The markup codes tell the processor just about everything about the application needs to know about it.
A processor does not processes all markups. HTML documents are processed by browsers, RTF documents
are processed by word processors.
What is the difference between open and closed language?
The Specifications for an open language is publicly available and any vendor can create an processor for it.
For example - RTF, HTML.
The specification for a closed language is not publicly available and vendors do no have access to the rules of
the markup language and can not create a processor for it. For example - Microsoft Word uses an closed
markup for its documents and only Microsoft' s word processor only can process word documents.
Problems in Markups
Difficult to identify the structure of the document
Looseness in structure makes it difficult to interpret
Lack of rules makes difficult to create a processor for it
Specific and generalized markup
Specific markup languages are used to generate code that is specific to particular application and device. They are
often built to serve a particular need. For example - RTF is used to format texts for printing and displaying, HTML is
used to format documents for web.
Generalized markup languages are used to describe the structure and meaning of a document but they do not
define how the document should be processed. SGML , XML are generalized markup languages.
SGML
Stands for Standard Generalized Markup Language
SGML is used for the structure of document but not its formatting
It is extensible - it allows a author to create his/her own structure
It is actually a metalanguage - it allows you to create your language.
Both HTML and XML originated from SGML. XML is a subset of SGML. HTML is an application of SGML
HTML vs. SGML
SGML
Generalized language
Extensible
Used to describe the structure of a document
HTML
Not generalized
Not extensible
Used to format and layout documents on web
There are also differences in coding

XML_r15 Page 2

Chapter 02-03: XML basics


Saturday, July 14, 2012
8:40 PM

Homework:

Today's Topics:

Important Points:

XML_r15 Page 3

Understanding XML
HTML vs. XML
SGML vs. XML
Goals of XML
Use of XML
XML standards

Chapter 02 - Entering into XML


Saturday, July 14, 2012
3:00 PM

What is XML?
XML is a subset of SGML
XML is used to describe the structure and meaning of document
XML allows you to create own vocabularies (tag)
XML is extensible; you can create other language using XML
HTML vs. XML
Look at the HML below
Look at the XML below
<HTML>
<books>
<HEAD><TITLE>Books in store</TITLE>
<book>
<name>XML</name>
</HEAD>
<BODY>
<price>700.00</price>
<TABLE>
</book>
<book>
<CAPTION>Price
<name>HTML</name>
List</CAPTION>
<price>350.00</price>
<TR>
<TH>Name</TH><TH>
</book>
Price</TH>
</books>
</TR>
<TR>
<TD>XML</TD>
<TD>700.00</TD>
</TR>
<TR>
<TD>HTML</TD>
<TD>350.00</TD>
</TR>
</TABLE>
</BODY>
</HTML>
The HTML above tells the browser how to
format the contents
HTML is about displaying

The XML above describe information (data) but does not


indicate what to do with it or how to display
XML is about describing

Why XML is needed?


HTML can display data but can structure and describe data.
We need language that is formal but not limited
So comes XML, XML is extensible and can be used to exchange data among applications
XML is not replacement of HTML but actually complementary to HTML
XML describes data to our application and HTML format and displays data
SGML vs. XML
XML is a descendant SGML
But XML is simpler and smaller than SGML
Obviously, there are some similarities. But there are extra things in XML
XML derived from SGML and optimized for World Wide Web
How XML relates to SGML?
XML is generalized like SGL; you can define your own tag sets
XML is self-describing
XML documents can be validated against the rules defined in DTD
What are extra things included in XML?
XML is simpler and smaller than SGML
XML includes an hyperlinking scheme , which is described as a separate language called Extensible
Linking Language (XLL)
XML includes a specification for style language called Extensible Stylesheet Language (XSL). XSL can
transform an XML document into another format.

XML_r15 Page 4

Chapter 02 - Entering into XML


Saturday, July 14, 2012
8:45 PM

How XML is used


XML is self-describing.
Each XML is created based on some rules defined in DTD
So XML can be used to describe the structure meaning our data.
XML can be used to work with data. A few example :
XML can be used as data interchange format. Since XML uses text-format standards based, data in one
application can be converted to XML which can easily be used by other applications.
XML can be used for Web Data. Data content for web page can stored in XML and HTML can be used
to format and display that data.
XML can be used as common data store that can be used in various different ways or by different
applications
How XML is processed?
XML is processed using parsers. Parsers breaks down the XML elements and generally creates a tree structure
which can be manipulated by an application.
What is parsing?
Parsing means breaking down a document into its constituents parts and understand the structure of the
document and the relationships of the its parts.
Goals of XML
The goals of XML as defined by the creators of XML specifications:
XML shall be straightforwardly useable over the internet
XML shall support a wide variety of applications
XML shall be compatible with SGML
It shall be easy to write programs which processes XML
The number of optional feature is to be kept minimum, ideally zero
XML documents should be human-readable and reasonably clear
The design of XML should be formal and concise
XML documents shall be easy to create
Terseness in XML markups is of minimal importance
XML - recommendation and standards
Current specification
XML 1.0 specification is currently approved as a recommendation by the W3C.
MathML (Mathematical Markup Language)
MathML is derived from XML. It is used to create mathematical formulae and scientific content on the web
RDF ( Resource Description Language)
RDF is used for describing metadata
XLL ( XML Linking Language)
It is a mechanism for linking XML documents
SMIL (Synchronized Multimedia Integration Language)
It is intended to use TV-Like multimedia on the web
XSL (Extensible Stylesheet Language)
It is a text-formatting language and is used to convert XML documents into various display format.

XML_r15 Page 5

DTD Basics
Saturday, July 14, 2012
8:41 PM

Homework:

Today's Topics:

You want to create XML document


describe Trainees data
Trainees XML document will hold data
more than one trainee
Each trainee will have
traineeid - id of the trainee
name
batch
Batch will contain
round - round number of
the course
course - which course is
assigned to the batch
Create a DTD document to content
model for you XML document elements
Create an sample XML document and
validate it with the DTD.

Important Points:

XML_r15 Page 6

What is DTD
Valid documents
Internal and External DTD
How to write DTD
Anatomy of DTD
Working with element and
element content model
Sequence
Choice

DTD - Basics
Saturday, July 14, 2012
8:41 PM

DTD - Stands for Document Type Definition


What is DTD?
DTD specifies the grammar rules for the particular type XML document.
What a elements an XML document should contain and what contents the elements should contain are
defined using DTD.
By associating a DTD rule with XML documents you can make sure, XML documents are written conforming
to certain standards.
A DTD defines allowable elements, attributes and their content model for a certain class XML document.
Well-formed vs. Valid XML document
A well-formed XML written with valid XML syntaxes and its elements properly nested.
A valid XML is written following the rules defined in a DTD for the documents and its elements, attributes and
content model matches the DTD definitions
A well-formed XML document is not always valid but a valid XML document is always well-formed. Why?
How to write DTD?
DTD definitions or reference are defined just after the XML declaration and before the root element
DTD definitions or reference is declared in DOCTYPE element
DTD can be internal or external
Internal DTD rules are defined in the XML document itself
<? xml version='1.0' ?>
<!DOCTYPE documentelement [.. DTD definitions..]>
<documentelement>
.
.
</documentelement>
External DTD are defined in separate document and that DTD file is referenced in XML document
<?xml version='1.0'?>
<!DOCTYPE documentelement external DTD reference..>
<documentelement>
.
.
</documentelement>
documentelement is the root element. The element name just after the DOCTYPE must match the root element

Things to know about Parsers


Parsers reads the xml document and realizes the structure of the document and breaks it down into form that you
can manipulate it in an application program
Parsers generally transform the xml into a tree structure inside the computer RAM
There two types of parsers
Non-validating parsers - only checks well-formness of XML
Validating parsers - it checks well-formness and it also validates the against some DTD rules or Schema definition
IE is not a validating parser by default But you can use it for validating you XML s against DTD rules.
To do this you need to install DTD validation components.
Collect it

XML_r15 Page 7

Chapter 4: Playing with DTD


Saturday, July 14, 2012
8:42 PM

Internal DTD
Lets write some DTD rules
Ex. #1 Internaldtd.xml
<?xml version='1.0'?>
<!DOCTYPE contact [
<!ELEMENT
contact (#PCDATA)>
]>
<contact>907865</contact>
The DTD declaration says that the document is about contact (root element or document element)
Inside definition, it declares an element contact whose content model is declared inside parenthesis ()
contact can contain PCDATA ( Parsed character data)
[You already have learnt about PCDATA]
External DTD
Ex. #2 contact.dtd
<!ELEMENT
contact (#PCDATA)>
externaldtd.xml
<?xml version='1.0'?>
<!DOCTYPE contact SYSTEM "contact.dtd">
<contact>907865</contact>
The contact.dtd defines only one element
The contact.dtd is referenced in externaldtd.xml
NOTICE use of SYSTEM, it is called SYSTEM identifier
External DTD can be referenced using
1. SYSTEM identifiers: it is used to reference a DTD file on your local computer
2. PUBLIC identifier : It uses a specialized identifier to locate actual DTD file
Example:
<!DOCTYPE trainee PUBLC "-//IDB-BISEW//Trainee Description //EN" "trainee.dtd">
Lets work with example

Ex #1
Open notepad and write
<?xml version="1.0" ?>
<!DOCTYPE person [
<!ELEMENT person (name, phone ) >
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<person>
<name>Habibul Haq</name>
<phone>9870760</phone>
</person>
Save the file and name it internaldtd.xml
Validate it
Is it successful?

Remove the <name>Habibul Haq</name> element


Validate it
Is it successful?

Ex #2
Open notepad and write
<!ELEMENT person (name, phone ) >
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
Save the file and name it person.dtd
Open notepad and write
<?xml version="1.0" ?>
<!DOCTYPE person SYSTEM "person.dtd">
<person>
<name>Habibul Haq</name>
<phone>9870760</phone>
</person>
Save the file and name it externaldtd.xml
Validate it
Is it successful?

Remove the <name>Habibul Haq</name>


element
Validate it

If not, why?

XML_r15 Page 8

DTD - Document type definition


Saturday, July 14, 2012
5:10 PM

Anatomy of DTD

Element

Content Model

Parsed Character
Empty
Element (s)

Sequence

CDATA

Choice
Cardinality ([nill] , *, ?, +)

Mixed
Any

Attribute

Values

Types
ID
IDREF
IDREFS
ENTITY
ENTITIES
NMTOKEN
NMTOKENS
Enumerated List

Constraints

Entity

Built-in & Character


General
Parameter

Notation

XML_r15 Page 9

DEFAULT VALUES
Fixed Values
Required (REQUIRED
Optional (IMPLIED)

Chapter 4: Playing with DTD


Saturday, July 14, 2012
8:42 PM

Element CONTENT model


#PCDATA - you already learned about that
EMPTY - it means element contains nothing. If
element has any content it will not be valid.
[#PCDATA allows empty content as well as character
contents]
ELEMENT
An element can have other child elements
Children can be in sequence
There can choice of elements, alternative sets of
children can be possible
You can define cardinality - how many times a
element can appear in a content model.
Lets play with sequence
Ex. #3 Sequence.dtd
<!ELEMENT book ( isbn, name, author, price )>
<!ELEMENT isbn (#PCDATA)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT author ( first, last ) >
<!ELEMENT first (#PCDATA) >
<!ELEMENT last (#PCDATA) >
<!ELEMENT price (#PCDATA)>
This DTD defines that book element has child elements isbn,
name, author and price. The author lement contains first
and last element.
The XML must maintain these sequence. You can not place
name before isbn
Lets examine it
Sequence.xml
<?xml version='1.0'?>
<!DOCTYPE book SYSTEM "sequence.dtd">
<book>
<isbn>760-987-098-11</isbn>
<name>XML</name>
<author>
<first>Jon</first>
<last>Smith</last>
</author>
<price>900.00</price>
</book>
Validate it
Now look the following xml
sequenceinvalid .xml
<!DOCTYPE book SYSTEM "sequence.dtd">
<book>
<name>XML</name>
<isbn>760-987-098-11</isbn>
<author>
<last>Smith</last>
<first>Jon</first>
</author>
<price>900.00</price>
</book>

Validation fails because


The content of element type "author" must
match "(first,last)".
The content of element type "book" must match
"(isbn,name,author,price)".
2 Errors
Lets examine choice of elements
Ex. 4. Choice1.dtd
<!ELEMENT person ( name | (fist-name, lastname))>
<!ELEMENT name (#PCDATA)>
<!ELEMENT first-name (#PCDATA)>
<!ELEMENT last-name (#PCDATA)>
It defines that person element can have either
name or first-name and last-name
Choice1.xml
<?xml version='1.0'?>
<!DOCTYPE person SYSTEM "choice1.dtd">
<person>
<name>Habib</name>
</person>
Validate the document.
Lets examine Cardinality
Ex. #5. acrdinality1.dtd
<!ELEMENT books (book)*>
<!ELEMENT book (name, price)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT price (#PCDATA)>
Look at books (book)* - it indicates books
element can contain zero, one or more book
elements.
Cardinality1.xml
<?xml version='1.0' ?>
<!DOCTYPE books SYSTEM "cardinality1.dtd">
<books>
<book>
<name>XML</name>
<price>700.00</price>
</book>
<book>
<name>HTML</name>
<price>300.00</price>
</book>
</books>
Validate the XML document.

XML_r15 Page 10

Class 3: Playing with DTD (Ch 4)


Saturday, July 14, 2012
9:37 PM

Homework:

Today's Topics:

You have to create DTD rules for trainees schema


As described
Element Content/Attributes
Trainees Root element
Contains one or more trainee
Trainee Contains:
traineeid - required attribute with
unique value
name element - text data
course -element - text data
batch element - is a element
Batch

Batchid element-textual data


tsp element - text data

Important Points:

XML_r15 Page 11

Anatomy of DTD
Working with element and
element content model
Sequence
Choice
Cardinality
Attributes
Attribute - data types
Constraints
Entities
What are they
Types
Syntax
Workouts

DTD Basics
Saturday, July 14, 2012
9:41 PM

Cardinality indicators
? means 0 or 1
+ means 1 or more
* means 0 or more
If no cardinality is defined then the element must appear
once and only once
Lets work with an example
Ex. #6 cardinality2.dtd
<!ELEMENT trainee (id, name, contact?, email+)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT contact (#PCDATA)>
<!ELEMENT email (#PCDATA)>

contact? - contact is optional


email+- there may be 1 or more email for one trainee
Cradinality2.xml
<?xml version="1.0"?>
<!DOCTYPE trainee SYSTEM "cardinality2.dtd">
<trainee>
<id>1078690</id>
<name>Asad</name>
<email>asad@gmail.com</email>
<email>asad@yahoo.com</email>
</trainee>
Validate the document
Attributes
Attribute Declaration
<!ATTLIST element list_of_attributes_declared>
Attribute is declared using Keyword ATTLIST
Attribute list includes
Attribute_name attributetype USE|Values Declartion)
Attribute Type
It indicate how the value of an attribute will be
handled
Supported Attribute types & meaning
Type

Description

CDATA

Value is character data

ID

Value of the attribute in unique in the


document

USE - refers whether the attribute is required


or optional
#IMPLIED - the attribute is optional
#REQUIRED - the attribute must be
present within the element
#FIXED - value of the attribute is fixed
Value Declaration includes
Value list
default values
Example
<!ATTLIS book genre CDATA #IMPLIED>
book element has a attribute genre
which will contain character data. The
genre attribute is optional
<!ATTLIST book book_id ID #REQUIRED >
book_id attribute value should be unique
in the document
More example:
<!ATTLIST genre NMTOKEN #RQUIRED>
It means that it has valid name. The
name here is confusing. In case of
programming variable you use some
names and there are some rules. Its like
that. There is some rules about
NMTOKEN.
<book genre="Classic Books"> NOT valid
as space is not allowed, it must be a
single word
<book genre="Classic"> valid
<!ATTLIST genre CDATA
(Classic|Autobigraphy|Others)
#REQURED>
genre can have one of the possible
values -Classic, Autobiography or
Others.
<!ATTLIST genre CDATA
(Classic|Autobigraphy|Others) "Others">
genre can have one of the possible
values -Classic, Autobiography or
Others. But the default value is Others.
<!ATTLIST book genre CDATA #IMPLIED
isbn CDATA#REQUIRED>

IDREF/IDREFS IDREF refers an unique element in the


document, IDREFS refers more than one
ENTITY/ENTI
TIES

10:42 PM

Lets Work with an example


Ex #1

Will be discussed next session

NMTOKEN/N NMTOKEN value is a valid names


MTOKENS
conforming XML element naming rules.
NMTOKENS has more than one separted by
a space
Enumerated
values

book element has two attributes: genre


and isbn
genre is optional but isbn is required

A list possible values

XML_r15 Page 12

A DTD describing people

<?xml version="1.0"?>
<!DOCTYPE person [
<!ELEMENT person (name+, profession*)>
<!ELEMENT name EMPTY>
<!ATTLIST name first CDATA #REQUIRED
last CDATA #REQUIRED>

DTD -Example
Tuesday, July 29, 2008
10:42 PM

<!-- The first and last attributes are required to


be present
but they may be empty. For
example,
<name first="Cher" last=""> -->
<!ELEMENT profession EMPTY>
<!ATTLIST profession value CDATA #REQUIRED>
]>
<person>
<name first="Alan" last="Turing"/>
<profession value="computer scientist"/>
<profession value="mathematician"/>
<profession value="cryptographer"/>
</person>
Ex #2
<?XML version="1.0"?>
<!doctype Thesis [
<!ELEMENT Thesis (p*)>
<!ELEMENT p (#PCDATA)>
]>
<Thesis>
<p>
In this thesis, I hope to get my Ph.D.
</p>
<p>
A Ph.D. is great to impress friends.
</p>
<p>
Hopefully I'll get a job.
</p>
</Thesis>
Ex #3
Books.dtd
<!ELEMENT books ( book* )>
<!ATTLIST books count CDATA #IMPLIED>
<!ELEMENT book ( isbn, name, author+,
description, publish-date )>
<!ATTLIST book bid ID #REQUIRED print
(paperback | whiteprint) #REQUIRED>
<!ELEMENT isbn (#PCDATA)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT author ( first, last ) >
<!ELEMENT first (#PCDATA) >
<!ELEMENT last (#PCDATA) >
<!ELEMENT description (#PCDATA | b)*>
<!ELEMENT b (#PCDATA)>
<!ELEMENT publish-date ( date | ( edition,
date)+ )>
<!ELEMENT date (#PCDATA) >
<!ELEMENT edition (#PCDATA) >
Books.xml
<?xml version="1.0"?>
<!DOCTYPE books SYSTEM
"book_attribute.dtd">

<books >
<book bid="b001" print="paperback">
<isbn>109-998-997-8080</isbn>
<name>All Quiet on The Western Front</name>
<author>
<first></first>
<last></last>
</author>
<description>
This is a <b>Great</b> book on war!!!
</description>
<publish-date><date></date></publish-date>
</book>
<book bid="b002" print="whiteprint">
<isbn>109-998-997-8080</isbn>
<name>All Quiet on The Western Front</name>
<author>
<first></first>
<last></last>
</author>
<author>
<first></first>
<last></last>
</author>
<description>
This is a <b>Great</b> book on war!!!
</description>
<publish-date>
<edition>1st</edition>
<date>12-02-04</date>
<edition>2nd</edition>
<date>12-02-06</date>
</publish-date>
</book>
</books>
Entities
An entity is a declared content that is referenced in the
document.
Entities can be parsed or unparsed and also can be part
of the document or external to the document.
An entity is declared once but can be referenced many
times.
When an entity is referenced, processor retrieves the
content of the entity and the content is inserted at the
point where the entity is referenced
Various types of entities
Parsed entities
The content of an parsed entity is extracted
(parsed) by XML parsers. So it can not contain
symbols or keywords reserved for XML.
Unparsed entities
An unparsed entity is often called binary entity. Its
content is not directly parsed by XML parsers. It
uses extra information provided by NOTATION
declaration to manipulate an unparsed entity. An
unparsed generally references binary file such
images.

XML_r15 Page 13

Chapter 04/05 - DTD (cont'd)


Internal entity
The content of an internal entity is defined in its
declaration. An Internal entity is always define text
content.
External Entity
An external entity refers a content unit that reside
inside its declaration. It refers to a location where its
content can be found.
Parameter entities
It allows you to create reusable section of text that can
be used many times in DTD declarations. It is never
referenced in XML content. It is only used within the
DTD . It only provides certain DTD writing facilities
Predefined entities
In XML there already some (five) entities built into it.
You need not to declare them to use.
They are
&amp; - the & character
&lt; - the < character
&gt; - the > character
&apos; - the ' character
&quot; - the " character
These are called built-in entities. Because all XML
parsers support these by default.
Syntax of Entity declaration
An entity is declared with ENTITY keyword
Parsed entity
<!ENTITY entityname "CONTENT Text here">
Unparsed (binary) entity
<!ENTITY entityname SYSTEM|PUBLIC "Resourse
Location" NDATA notationidentifier>
NDATA - means it needs NOTAION to manipulate the
entity content
Notaionidentifier - a name defined by OTATION
[NOTATION actually provides information which
external application to be used to extract certain type
of resource
<!NOTAION JPG SYSTEM "iexplore.exe">
It tells to use iexplore.exe to JPG type file
<!ENTITY pic SYSTEM "MyPic.jpg" NDATA JPG>
It tells the processors that entity pic is JPG type
resource. The processor will use JPG NOTAION to
process this entity ]
Syntax of Entity Reference
Syntax is
&entityname;
Suppose you declared an entity like below
<!ENTITY author "Md. Habibul Haq">
Then you will reference it like below
&author;

XML_r15 Page 14

Lets work with an example.


You have a file dogdata.txt with following
content
Dogs were wild in ancient time. But they
are now domesticated.
Now create the entity.dtd file
<!ENTITY dog-source SYSTEM "dog.txt">
<!ENTITY cow-source "Cow is the most
common domestic animal.">
<!ELEMENT animals (animal*)>
<!ELEMENT animal ( name, description)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT description (#PCDATA)>
Now create the entity.xml file
<?xml version="1.0"?>
<!DOCTYPE animals SYSTEM
"entity.dtd">
<animals>
<animal>
<name>Dog</name>
<description>&dogsource;</description>
</animal>
<animal>
<name>Cow</name>
<description>&cowsource;</description>
</animal>
</animals>
Parse it and see the result
Parameter entity
An Parameter Entity is declared and
referenced within the DTD
It gives you code-writing ease. Suppose
you have the following DTD
<!ELEMENT relative (name,
contact)>
<!ELEMENT friend (name, contact )>
<!EELEMNT colleague (name,
contact )>
Look (name, price ) is used several times.
You can do it like below using parameter
enetity
<!ENTITY % content "(name,
price )">
<!ELEMENT relative %content;>
<!ELEMENT friend %content;>
<!EELEMNT colleague %content;>
It uses % sign in declaration and reference
Syntax of declaration:
<!ENTITY % enityname "content
here">
Syntax of reference:
%entityname;

Some problems
#1
A family consists of father, mother and
children. Some families have no children

Chapter 04/05 - DTD (cont'd


Saturday, July 14, 2012
7:59 PM

Parameterentity.dtd
<!ENTITY % carnv-model " ( name, prey,
habitat)">
<!ENTITY % harv-model " ( name, food, habitat )
">
<!ELEMENT animals ( carnivore | harbivore ) >
<!ELEMENT carnivore %carnv-model; >
<!ELEMENT harbivore %harv-model; >
<!ELEMENT name (#PCDATA)>
<!ELEMENT prey (#PCDATA)>
<!ELEMENT food (#PCDATA) >
<!ELEMENT habitat (#PCDATA)>
Parameterentity.xml
<?xml version="1.0" ?>
<!DOCTYPE animals SYSTEM
"parameterentity.dtd">
<animals>
<carnivore>
<name>Chitah</name>
<prey>Springbuck, Gazelle</prey>
<habitat>African grass
plain</habitat>
</carnivore>
</animals>

Important points

XML_r15 Page 15

Describe the family document type using DTD

A course contains one or more modules.


Defile it in DTD.

Chapter 5 : Scripting XML


Saturday, July 14, 2012
8:43 PM

Homework:

Today's Topics:

You have the following XML file


message.xml
<message receive-time="Jan 30, 2009
1930:">
<from>Sales, OMG</from>
<to>Mr. Mahbub, BITL</to>
<subject>Discount
Offer</subject>
<body>
Season end offer strats.
Check our web portal
</body>
</message>
Load the information on an HTML page
using JavaScript.

Important Points:

XML_r15 Page 16

JavaScript basics
DOM basics
Accessing XML data using JavaScript
Workouts

Introduction to JavaScript
Saturday, July 14, 2012
8:00 AM

HTML and XML


HTML shows your interface on the web
XML holds your data in structured way and which
can be manipulated easily
HTML & XML both working together can easily
create a data-driven web page for you
But there must be some programming tool in
between them. You can use JavaScript as one of that
tools.

Variables
JavaScript is not a strongly typed language
You do need to declare data type for your variables
To create a variable, use var keyword.
var a;
a = 213;
var traineeName = "Enamul Haque";
A variable may not be a Javascript reserved word or
begin with a number or any symbol other than $ and
_ signs.
You can store any type of value in same varibale

Syntax, constructs , operators..


JavaScript uses C like syntax. For a VB programmer,
at beginning things may come clumsy. Here a brief
overview for you

JavScript

Operator Description
Web Page

XML

JavaScript

It is not a full-fledged programming language.


JavaScript statements can be embedded directly in
an HTML page.
It is called client script.
It runs inside the client browser.
It can add dynamic behavior to you web page.
Before beginning we must learn basics
Writing JavaScript - where should I write scripts?
We add JavaScript code in HTML files in two ways
Inline JavaScript: JavaScript file is embedded
directly inside HTML.
To define a JavaScript block in your web
page, simply use the following block of
HTML.
<script type='text/javascript'>
// Your script goes here.
</script>

You can place these script blocks anywhere


on the page that you wish, there are some
rules and conventions however. The ideal
place is <HEAD> .. </HEAD> Section
External JavaScript: You can write your
JavaScript code in a different file and
associate it with you HTML files. External
JavaScript code file is saved with
extension .js.
Including an external file is basically the
same as doing an in-line script

Addition (also string concatention)

Subtraction

Multiplication

Division

Remainder of division (or modulus)

++

Increment

--

Decrement

var x =
var y =
// y=5,
var x =

5;
x++;
x=6
5; var y = ++x;

// y=6, x=6

Additional shorthand operators exist when working


on the same variable. For instance
x = x + 5;
Is same as x += 5;
Logical and Comparison Operators
Operator Description
=

Asignment, var x; x = 5;

==

Equality, is x==5?

!=

Not equal, 6!=5 yields true

>

Greater than, 6 > 5 yields true

<

Less than, 5 < 6 yields true

<=

Less than or equal, 5<=5 yields true

>=

Greater than or equal, 5>=5 yields true

&&

And, (x==5) AND (y==5)

||

OR, is (x==5) OR (y==5)

<script type='text/javascript'
src='scriptfile.js'></script>

XML_r15 Page 17

everything to the end of the line.

Introduction to JavaScript

var x=5;
// Everything from the
// to end of line is ignored

Saturday, July 14, 2012


8:00 AM

Decision constructs
The if statement lets you execute a block of code if
some test is passed.
var x=5;
if (x==5)
{
alert('x is equal to 5!');
}

/*
Comment
Comment
*/

You can also use an else clause to execute code if the


test fails.
var x=5;
if (x==5)
{
alert('x is equal to 5!');
}
else
{
alert('x is not equal to 5!');
}

Loops: WHILE
while loops in Javascript also follow basic C syntax
and are easy to understand and use.
The while loop will continue to execute until its test
condition evaluates to false or the loop encounters a
break statement.
var x
while
{
x
}
var x
while
{
x

= 1;
(x<5)
= x +1;
= 1;
(true)
= x + 1;
if (x>=5) {

break;

Block quotes begin a comment block with a slashasterisk (/*) and Javascript will ignore everything from
the start of the comment block until it encounters an
asterisk-slash (*/).

Loops: FOR
The for loop follows basic C syntax, consisting of an
initialization, an evaluation, and an increment.

Comments
Javascript supports two types of comments.
Double-slashes (//) tell javascript to ignore

function doSomething()
{
// code
}
function doMoreThings( a, b )
{
//code
}

Output (writeln)
The first method is to use the document.writeln(string)
command.
This can be used while the page is being constructed.
Here's how a simple web-page will look...
<html>
<head> </head>
<body>
<script type='text/javascript'>
document.writeln('Hello World!');
</script>
</body>
</html>

As the page is loading, JavaScript will encounter this


script and it will output "Hello World!

for (var i=0; (i<5); i++)


{
document.writeln('I is equal to
'+i+'<br>');
}
// outputs:
// I is equal to 0
// I is equal to 1
// I is equal to 2
// I is equal to 3
// I is equal to 4

Function
A JavaScript function is written with function keyword
function can accept parameters

Output (alert)
The second method is to use a browser alert box.
<html>
<head> </head>
<body>
<script type='text/javascript'>
alert('Hello World!');
</script>
</body>
</html>

Output (getElementById)
The last method is the most powerful and the most
complex (but don't worry, it's really easy!).
You can give each and every element in HTML a
unique identifier (an ID), and Javascript can find
elements you have labeled and let you manipulate
them.

XML_r15 Page 18

Introduction to JavaScript
Saturday, July 14, 2012
8:00 AM

check out the code!


<html>
<head> </head>
<body>
<div id='feedback'></div>
<script type='text/javascript'>
document.getElementById('feedback').inne
rHTML='Hello World!';
</script>
</body>
</html>

JavaScript Events
JavaScript supports events
The documents, for m element fires events
When a HTML page finished, load event is fired. When
a user clicks on a button, a click event is fired.
To write code for an event, we use onxxx attribute,
xxx is the eveent name
For example
<input type"button " value="Click Here"
onclick="alert( 'Hi');">

Whenever user click the button, an alert box is shown.


Mostly, we run function in response to events
Check the code
<html>
<head>
<script>
function changeColor()
{
document.bgColor="#e4e4e4";
}
</script>
<body onload="changeColor();">
.
</body>
</html>

document.bgColor - the background color of the


web page
document.formLogin - returns the form which
has been given name formLogin
document.formLogin.txtname - returns the text
field inside the form, which has name txtname
document.formLogin.txtname.value - returns
what the user entered inside the text field
To access an element which has id attribute
value , use getEelemntById method of document
object
To access <div id="msg"></div> ,
usedocument.getElementById( "msg" )
document.getElementById( "msg" ).text
="Java Script" - set the "Java Script" inside
the div element
document.getElementById( "msg").innerHT
ML = "<b>Java Script</b>"
sets the "<b>Java Script</b>" inside the div
element

Things to know
JavaScript is case sensitive
A JavaScript statement ends with ; (though ; is not
required , if you write on statement on one line. But
putting ; is good practice)

<html>
<head>
<title>Test</title>
</head>
<body>
<form name="formLogin">
User name: <input type=text
name="txtname"><br>
Password: <input type="password"
name="txtpass"><br>
<input type="submit"
value="Login">
</form>
<div id="msg"></div>
</body>
</html>

JavaScript Basics
It is a object based language.
The top level object is window.
window.location - returns the address bar of the
browser
Window.documet - it returns the document part of
the web page
window is the default object, so, window.document is
equivalent document.
An example:
Suppose you created a web page using the following
HTML:

Document Object Model (DOM)


DOM is a standard way of representing XML
documents
DOM parsers parse the XML documents and
create the DOM tree for you applications.
Every thing in the DOM tree is Node
Say we have xml document as shown
<books>
<book>
<name>XML</name>
</book>
<book>
<name>XML</name>
</book>
</books>

The Node object has methods and properties


that allow to manipulate elements

XML_r15 Page 19

We have xml file books.xml


<?xml version='1.0'?>

JavaScript Basics
Saturday, July 14, 2012
8:00 AM

<books>
<book id="B01">
<name>XML</name>
<price>700.00</price>
</book>
<book id="B02">
<name>HTML</name>
<price>300.00</price>
</book>
</books>

The DOM tree will be like


books

book

book

Lets parse it using JavaScript


name

name

XML

HTML

var doc = new


ActiveXObject( "microsoft.xmldom");
doc.load( "books.xml");

var root = doc.documentElement;

After parsing your document is also a node


If you access documentElement, you will get the root
Node exposes some methods and properties
childNodes - returns the children of the current
node
firstChild - returns first child
lastChild - returns the last child
selectNodes( expression )- returns nodes that
matches the expression
selectSingleNode (expression) -returns the nodethat
matches the expression
getAttribute( attrributename) - returns the value of
the attribute
text - returns the text inside the element
Parsing XML with JavaScript
In windows we mostly use MSXML parser
Steps are
Create an instance of the msxml parser
var doc = new
ActiveXObject( "microsoft.xmldom");

Parse the XML


doc.load( "xmlfile.xml");

//use doc.loadXML( "xml string" );


Manipulate XML
Accessing XML element with JavaScript
MSXML is DOMparsers
XML DOM (Document Object Model) is a interface for
programmer to access nodes in a XML element tree
DOM basics
DOM exposes a programming interface to access node in
XML tree
DOM treats everything as a node
documentElement - returns the root element in a XML
tree
Lets explore with an example

Now root holds the top books element with


children
<books>

</books>
root.childNodes - returns two books under the top
books element
var bkXml = root.chilNodes.item(0)
Now bkXml holds
<book id="B01">
<name>XML</name>
<price>700.00</price>
</book>

bkXml.getAttribute("id" ) will return B01


bkXml.firstChild.text will return XML
bkXml.childNodes.item(1) will return 700.00
Now try an Example:
Book.xml
<?xml version="1.0"?>
<book>
<name>SQL</name>
<price>700.00</price>
</book>

We want to show book information from xml file on


an HTML page
Book.html

XML_r15 Page 20

<html>
<head> <title>Book info</title>
</head>
<body>
<h3>Book info</h3>
Name: <span id="bn"></span>
<br>
Price: <span id="bp"></span>
</body>
</html>

Scripting XML
Saturday, July 14, 2012
8:34 PM

<span id="bn"></span> and <span id="bp"></span>


are placeholders for the name and price of the book
To show the data from XML, we will write a JavaScript
function and which will be called in load event of body.

The function is written in the head section


<script>
function loadXML()
{
var xmlDoc = new
ActiveXObject( "Microsoft.XMLDOM"
);
xmlDoc.load( "bookjs.xml" );
var root = xmlDoc.documentElement;
document.getElementById( "bn").inn
erHTML =
root.childNodes.item(0).text;
document.getElementById( "bp").innerHTML =
root.childNodes.item(1).text;
}
</script>
Now the function is called inside the body tag at onload
event.

The finished HTML is


<html>
<head> <title>Book info</title>
<script>
function loadXML()
{
//load the parsers
var xmlDoc = new
ActiveXObject( "Microsoft.XMLDOM" );
//parse the document
xmlDoc.load( "bookjs.xml" );
//find the root element, this the <book>
</book> element here
var root = xmlDoc.documentElement;
document.getElementById( "bn").innerHTML =
root.childNodes.item(0).text;
document.getElementById( "bp").innerHTML =
root.childNodes.item(1).text;
}
</script>
</head>
<body onload="loadXML();">
<h3>Book info</h3>
Name: <span id="bn"></span>
<br>
Price: <span id="bp"></span>
</body>
</html>

XML_r15 Page 21

Habib, BITL

More on Scripting XML and XML as Data


Saturday, July 14, 2012
9:00 AM

Homework:

Today's Topics:

You have a XML file as shown


<?xml version="1.0"?>
<trainees>
<trainee traineeid="1078909">
<name>Hasan Iqbal</name>
<email>hq@gmail.com</email>
</tarinee>
<trainee traineeid="1078991">
<name>Enamul Haque</name>
<email>enam@gmail.com</email>
</tarinee>
</trainees>
Show the XML data on HTML table using
XMLDSO as shown
Id

Name

Email

107890 Hasan Iqbal


9

hq@gmail.com

107899 Enamul
1
Haque

enam@gmail.c
om

Important Points:

Lecture Topic:
During the lecture, take notes here.

XML_r15 Page 22

More workouts on Scripting XML


XML as Data
XMLDSO ( XML Data Source Object )
Showing data in tabular Form
XML Data Islands
Showing data on tabular Form
Data Navigation - Showing Data one
row at a time

More on Scripting XML


Saturday, July 14, 2012
9:00 AM

Some Methods and properties of a Node in DOM


We will explores some methods with example
Say we have an XML file books.xml as below
<?xml version='1.0'?>
<books>
<book id="B01" genre="Academic">
<name>C Sharp</name>
<price>900.00</price>
<publisher>Que</publisher>
</book>
<book id="B02" genre="Classic">
<name>All Quiet on the Wester Front</name>
<price>1600.00</price>
<publisher>IPL</publisher>
</book>
</books>
We parsed the XML using DOM Parsers like below
var xmlDoc = new
ActiveXObject( "Microsoft.XMLDOM" );
//xmlDoc.async = false;
xmlDoc.load( "books_data.xml" );
var root= xmlDoc.documentElement;

Now roots holds the all the book elements along with
parent element books
You wrote
var book1 = root.childNodes.item(0)
book1 holds
<book id="B01" genre="Academic">
<name>C Sharp</name>
<price>900.00</price>
<publisher>Que</publisher>
</book>
You wrote
var bid = book.getAttribute("id")
bid holds value "B01"
getAttribute("attributname") - returns attribute value
of a node
You wrote
var books = root.getElementsByTagName("book")
books holds two book elements under books
getElementsByTagName( "elementname") - returns a
set of elements that matches the supplied tag
You wrote
var books = root.selectNodes( "book" )
books holds two book element under books
selectNodes( "pattern") - returns a set of elements that
matches the supplied pattern
[We will explore patterns later]

You wrote
var book =
root.selectSingleNode( "book[name='C Sharp']" )
book holds
<book id="B01" genre="Academic">
<name>C Sharp</name>
<price>900.00</price>
<publisher>Que</publisher>
</book>
selectSingleNode("pattern") - returns an
element that matches the supplied pattern
Now we will explore with an example
We will use books.xml as shown on the left
And We will create book_search.html
The interface will look like as below
Book Store
Seach Book B02

By Id

OR

By Name

Search result:
Id: B02
Name: All Quiet On the Western Front
Price: 1600.00
Publisher: IPL

Whenever an user enters ID or Name of a book


and Clicks any one of the two buttons, the
application will search the XML file and show
information of the book that matches the ID Or
name
[Source on Next Page]
Look we wrote some script
<script>
var xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
xmlDoc.load( "books_data.xml" );
var books= xmlDoc.documentElement;
function searchById()
{
//...
}
function searchByName()
{
//...
}
</script>
Look three lines before two function definitions
These three line will be executed as the HTML document
loads and Two variables xmlDoc and books will be
initiated .
Two buttons are created using the following HTML
<input type=button value="By ID" onclick="searchById();">
.
<input type=button value="By Name"
onclick="searchByName();">
Whenever users click on button one of the two functions
will be executed.
The functions will find what the user enters the text box
and finds matching books and then show information
inside the div element with id divmsg

XML_r15 Page 23

Scripting XML
Saturday, July 14, 2012
9:00 PM

<html>
<head>
<title>Book Store</title>
<script>
var xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
xmlDoc.load( "books_data.xml" );
var books= xmlDoc.documentElement;
function searchById()
{
var id = document.frm.bid.value;
var b=books.selectSingleNode( "book[@id='" + id +"']");
if( b == null )
{
document.getElementById( "divmsg" ).innerHTML = "book not found";
return;
}
var s = "Seach Result: <br>";
s += "ID: " + b.getAttribute("id" ) + "<br>";
s += "Genre: " + b.getAttribute("genre" )+"<br>";
s += "Name: " + b.childNodes.item(0).text+"<br>";
s += "Price: " + b.childNodes.item(1).text+"<br>";
document.getElementById( "divmsg" ).innerHTML = s;
}
function searchByName()
{
var bname = document.frm.bname.value;
var b=books.selectSingleNode( "book[name='" + bname +"']");
if( b == null )
{
document.getElementById( "divmsg" ).innerHTML = "book not found";
return
}
var s = "Seach Result: <br>";
s += "ID: " + b.getAttribute("id" ) + "<br>";
s += "Genre: " + b.getAttribute("genre" )+"<br>";
s+= "Name: " + b.childNodes.item(0).text+"<br>";
s+= "Price: " + b.childNodes.item(1).text+"<br>";
document.getElementById( "divmsg" ).innerHTML = s;
}
</script>
</head>
<body>
<form name="frm">
Seach Book : <input type="text" name="bid"><input type=button value="By ID" onclick="searchById();"> or
<input type="text" name="bname"> <input type=button value="By Name" onclick="searchByName();">
<br>
<br> <div id=divmsg style="font-family: tahoma; font-size: 8pt; border: 1px solid #e4e4e4; width:70%;padding:
5px;"></div>
</form>
</body>
<html>

XML_r15 Page 24

XML as Data - XMLDS O and XML Data Islands


Saturday, July 14, 2012
9:00 AM

Other technologies to incorporate XML Data


XMLDSO - XML Data Source object
You can use XML DSO to bind controls in a web
page with data
Example
Books.xml
<?xml version="1.0"?>
<books>
<book id="B01">
<name>XML</name>
<price>700.00</price>
</book>
<book id="B02">
<name>HTML</name>
<price>300.00</price>
</book>
</books>
Books.html
<html>
<head>
<script>
function start()
{
var doc = xmldso.XMLDocument;
doc.load( "books.xml");
}
</script>
<head>
<body onload="start();">
<object
classid="clsid:550dda30-0541-11d2-9ca9-0060b0e
c3d39" id="xmldso" >
</object>
<table datasrc="#xmldso">
<thead>
<tr>
<th>ID</th><th>Name</th><th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td><span datafld="id"></td><td><span
datafld="name"></td><td><span
datafld="price"></td>
</tr>
</tbody>
</table>
</body>
</html>
Xmldso is an ActiveX object and it has a classid
It is created using <object.>.</object> tag
In this HTML page the activex object has id
xmldso

Onload calls a function which loads the


Books.xml into DSO object t which has id
xmldso
The table is boud to xmldo with attribute
datasrc="#xmlso"
Eeach HTML element is bound to a data filed
using attribute datafld="xml element name"
XML Data Islands
It is another technology
It added to a web page using <xml..>
tag
The previous example is done here with
XML data island
<html>
<head>
</head>
<body>
<xml src="books.xml" id="xmldi"
async="false"></xml>
<table datasrc="#xmldi">
<thead>
<tr>
<th>ID</th><th>Name</th><th>
Price</th>
</tr>
</thead>
<tbody>
<tr>
<td><span datafld="id"></td><td><span
datafld="name"></td><td><span
datafld="price"></td>
</tr>
</tbody>
</table>
</body>
</html>

<xml > tag has a attribute src, which points


the location and name of the XML file
The HTML table has been bound to the data
source using attribute datasrc="#xmldi"
The data cell in the table has a span with
attribute datafld, its value indicates which
element or attribute to load on that HTML
element
Look <thead></thead> and <tbody>
</tbody>. These two are used to indicate
which part is the header part of the table and
which part is to load with data

XML_r15 Page 25

XML as Data
Saturday, July 14, 2012
9:00 AM

XML data islands


Another example - viewing one set of data at a time
Books_nav.html
<html>
<head>
<script type="text/javascript">
function movenext()
{
x=xmldso.recordset;
if (x.absoluteposition < x.recordcount)
{
x.movenext();
}
}
function moveprevious()
{
x=xmldso.recordset;
if (x.absoluteposition > 1)
{
x.moveprevious();
}
}
</script>
</head>
<body>
<xml src="books.xml" id="xmldso" async="false"></xml>

<p>
Title: <span datasrc="#xmldso" datafld="id"></span>
<br />Artist:<span datasrc="#xmldso" datafld="name"></span>
<br />Year:<span datasrc="#xmldso" datafld="price"></span>
</p>
<p>
<input type="button" value="Previous book"onclick="moveprevious()" />
<input type="button" value="Next book"onclick="movenext()" />
</p>
</table>
</body>
</html>
As HTML document loads the first record from the XML file is shown
Whenever an user clicks on Next Book button, the movenext() javascript function is called
It first get record from the using x.recordset
It checks whether currently last record is showing or not. x.recordcount returns the number rows in x and
x.abosuluteposition return the row number currently showing. Position satrts at 1. so if x.absoluteposition
< x.recordcount is true, we are not in the last record position and we can call x.movenext(). movenext()
method moves the position to next record.
Whenever an user clicks on Previous Book button, moveprevious() javascript function is called
It checks whether we are at first record position or not
If we are not at first position it moves to the previous record position

XML_r15 Page 26

Chapter 08 - XSL, XML with Style


Saturday, July 14, 2012
8:19 PM

Homework:

Today's Topics:

You have the following XML


<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl"
href="people.xsl"?>
<PEOPLE>
<PERSON>
<NAME>Mark </NAME>
<ADDRESS>911 Somewhere
Circle, Canberra,
Australia</ADDRESS>
</PERSON>
<PERSON>
<NAME>Tracey</NAME>
<ADDRESS>121 Zootle Road,
Cape Town, South
Africa</ADDRESS>
</PERSON>
</PEOPLE>
Show the data in HTML table as below
using XSL
Name

Address

Mark

911 Somewhere Circle,


Canberra, Australia

Tracey

121 Zootle Road, Cape Town,


South Africa

Important Points:

XML_r15 Page 27

XSL

What is it?
Templates and patterns
XSL loop
Multiple template
XSL functions

We want to display the information in the XML file on


HTML page as shown

XSL Basics
Saturday, July 14, 2012
8:21 PM

Trainee Info

XSL - Extensible Stylesheet language


XSL is used for converting XML to some other output.
The output may HTML, XML, RTF or PDF - generally
HTML or XML
Each XSL document is a description of how a XSL
processor can transform an XML document from one
structure into another.
It a formatting language written in XML syntax
XSL has the ability to transform an XML document into
some other output structure
XSL documents contains formatting rules to be applied
on some XML structure
XML Document Structure

Md. Enam Ahamed


Tarinee Id: 1098769
Course: ESAD-CS
Round: 7

XSL Formatting Rules

Transformation

Display Structure For Some media

XSL Style Sheets


An XSL Stylesheet consists of one or more templates
A template provides a structure for the output
document
Each template contains a pattern (expressed in XPath
notation)
[You have already been familiar with XPath]
A pattern in a template specify the XML elements to
which the template applies.
XSL namespace provides syntax and meaning of the
keywords used in XSL.
Example:
<xsl:template match="trainees/trainee">
.
</xsl:template>
The code fragment above create and template
containing formatting rules and also specifies to which
elements the formatting rules to apply. The above
template apply to all trainee elements under trainees.
Lets proceed with an example
Example #1
Suppose we have an XM file trainee.xml
<?xml version="1.0"?>
<trainee id="1098769">
<name>Md. Enam Ahmed</name>
<course>ESAD-CS</course>
<round>7</round>
</trainee>

Lets create XSL Document - trainee.xsl


<?xml version="1.0"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/trainee">
<html>
<head><title>Trainee Info</title>
</head>
<body>
<div style="border: solid 1px #e4e4e4;">
<b><xsl:value-of select="name"/></b<br/>
Trainee ID: <xsl:value-of select="@id"/<br/>
Batch: <xsl:value-of select="batch"/><br/>
Round: <xsl:value-of select="round" />
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
TheTop element is <xsl:stylesheet >
</xsl:stylesheet>
It create a standard namespace with prefix xsl
Everything must within this top-level element
Look it has a attribute version having value
"1.0", it is mandatory
An XSL document consists of at least one template
A template is created using
<xsl:template match="/trainee">
.
</xsl:template>
The template says that the rules inside it is to be
applied to trainee node under root.
<xsl:value-of select="name" /> says to insert the value
inside the name element under current node
<xsl:value-of select="@id" />says to insert the vale of
the id attribute of the current element
[Attribute name is prefixed with @ symbol]
Look HTML <br> is written as <br />. This is XHTML
syntax. Since we are writing HTML in XML syntax, we
must close every tag and properly nested
How to display the formatting output by XSL?

XML_r15 Page 28

<?xml version="1.0"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transf
orm" version="1.0">
<xsl:template match="/">
<html>
<head><title>Trainee Info</title>
</head>
<body>
<xsl:for-each select="trainees/trainee">
<div style="border-bottom: solid
1px #e4e4e4;">
<b><xsl:value-of
select="name"/></b><br/>
Trainee ID: <xsl:value-of
select="@id"/><br/>
Batch: <xsl:value-of
select="batch"/><br/>
Round: <xsl:value-of
select="round" />
</div>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

XSL
Saturday, July 14, 2012
9:27 PM

How to view XSL formatting output ?


Usually we use XSL processor for this task. We instruct the
XSL processor to convert an XML document applying an
XSL document. The XSL processor converts it and delivers
you the output.
We IE for this purpose
For this we need to insert a processing instruction for IE to
find XSL file
Change the as below
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="trainee.xsl"?>
<trainee id="1098769">
<name>Md. Enam Ahmed</name>
<course>ESAD-CS</course>
<round>7</round>
</trainee>
We added a processing instruction after xml declaration
<?xml-stylesheet type="text/xsl" href="trainee.xsl"?>
Open the XSL file using IE, view the output
Loops in XSL
XSL supports loops
xsl:for-each is used to loop through a set of nodes
It is created using
<xsl:for-each select="pattern">..</xsl:for-each>
Each a match is found the rule inside is applied
Suppose you wrote
<xsl:for-each select="tarinees/trainee">
<b><xsl:value-of select="name" /></b>
</xsl:for-each>
Each taime a trainee under trainees node is found,
the name of the trainee is formatted in bold-face

Now add the processing instruction in the xml


file as below
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl"
href="trainees.xsl"?>
<trainees>
.
</trainees>
View the output

Lets explore
Example #2
We have XML file - trainees.xml
<?xml version="1.0"?>
<trainees>
<trainee id="1098769">
<name>Md. Enam Ahmed</name>
<course>ESAD-CS</course>
<round>7</round>
</trainee>
<trainee id="1098709">
<name>Hasan IQbal</name>
<course>ESAD-VB</course>
<round>8</round>
</trainee>
</trainees>

Multiple templates template


An XSL file can contain multiple templates
A template can call another template based on
patter match
A template is called using <xsl:apply-templates
slect="pattern" />
Suppose you created templates as show
<xsl:template select="trainees">
<xsl:apply-templates
select="trainee/result" />
</xsl:template>
<xs:template match="result">
..
<xsl:template>
Look the first template calls the second
template
Each time a match for "trainee/result"

We will create an XSL file - trainees.xsl

XML_r15 Page 29

XSL
Saturday, July 14, 2012
11:06 PM

The same output we created in example #2 can be done using


multiple templates
Lets create the XSL file - trainees_template.xsl
<?xml version="1.0"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<html>
<head><title>Trainee Info</title></head>
<body>
<xsl:apply-templates
select="trainees/trainee" />
</body>
</html>
</xsl:template>
<xsl:template match="trainee">
<div style="border-bottom: solid 1px #e4e4e4;">
<b><xsl:value-of select="name"/></b><br/>
Trainee ID: <xsl:value-of select="@id"/>
<br/>
Batch: <xsl:value-of select="batch"/><br/>
Round: <xsl:value-of select="round" />
</div>
</xsl:template>
</xsl:stylesheet>
Now change the xml file as below
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl"
href="trainees_template.xsl"?>
<trainees>
.
</trainees>
See the output
XSL Functions
XSL supports a set of functions
Node-set functions
position() - returns the position of the node in a set of
nodes matched by a pattern
last() - returns - the position of the last node in a set of
nodes matched by a pattern
Summary functions
sum() - return the sum of values in a set of node
count() - returns the number of nodes matched by a
pattern
String function
substring() - exatcts a substring from a string
There are a lot more to explore

XML_r15 Page 30

Lets work with an example


Create the books.xml file
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl"
href="xsl_functions.xsl"?>
<books>
<book isbn="10-90-887-909">
<name>SQL ins and outs</name>
<author>Clerk</author>
<listprice>24.99</listprice>
<price>17.55</price>
<edition>4</edition>
<publisher>QUE</publisher>
</book>
..
</books>
Create the books.xsl
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Tran
sform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head><title>Using XSLT
functions</title></head>
<body>
<h3>Here are some use of XSL
functions:</h3>
Number of books:
<xsl:value-of select="count(books/book)"/>
<br/>
Number of 4th edition books:
<xsl:value-of
select="count(books/book[edition=4])"/>
<br/>
Last book in the list:
<xsl:value-of
select="books/book[position()=last()]/name"/
><br/>
Price of first book:
<xsl:value-of
select="number(books/book[position()=
1]/price)"/><br/>
Sum of price of all the books:
<xsl:value-of
select="sum(books/book/price)"/><br/>
First 3 character of 2nd book name:
<xsl:value-of
select="substring(books/book[position()=
2]/name, 1, 3)"/><br/>
Sum of price of all the books:
<xsl:value-of
select="sum(books/book/price)"/>
</body>
</html>
</xsl:template>

XSL - Chapter 08
Saturday, July 14, 2012
9:00 AM

Today's Topics:

Homework:
You have the following xml
<?xml version="1.0"?>
<tsps>
<tsp code="BITL">
<name>Bhuiyan IT Ltd.</name>
<address> H 59/A, H 7/A, Dhanmondi</address>
<web>www.bit.com</web>
</tsp>
<tsp code="HTCL">
<name>Hi-Tech It Ltd.</name>
<address>12th Fl. GB Bhaban, Mirpur</address>
<web>www.htcl.com</web>
</tsp>
</tsps>
Show the data in xml as below (using XSL)
TSP

Code

Address

Web

Bhuiyan IT Ltd. BITL

H 59/A, H 7/A, Dhanmondi www.bit.com

Hi-Tech IT Ltd. HTCL

12th Fl. GB Bhaban, Mirpur www.htcl.com

Important Points:

Lecture Topic:
During the lecture, take notes here.

XML_r15 Page 31

Conditional Processing
xsl:if
xsl:choose
Sorting

XSL - Conditional Processing


Saturday, July 14, 2012
9:00 AM

Conditional processing in XSL


You have two construct for this
xsl:if
xsl:choose

xsl:if element
The xsl:if element test a Boolean condition, if condition is
true, the contents inside the xsl:if construct is added to
result tree otherwise not
Syntax:
<xsl:if test="boolean expresson">
.
</xsl:if>
You wrote
<xsl:if test="result = 'A+'"></xsl:if>
If the value of the node result is equal to A+, the
contents inside the xsl:if will be processed
= is used to test equality
Legal operators are
= (equal)
!= (not equal)
&lt; less than
&gt; greater than
Lets work with an example
Example #6
Lets create Books.xml
<?xml version="1.0"?>
<books>
<book isbn="10-90-887-909" available="yes">
<name>SQL ins and outs</name>
<author>Clerk</author>
<listprice>24.99</listprice>
<price>17.55</price>
<edition>4</edition>
<publisher>QUE</publisher>
</book>
<book isbn="10-90-3467-819" available="no">
<name>Programming practice</name>
<author>Dave Hart</author>
<listprice>24.99</listprice>
<price>17.55</price>
<edition>4</edition>
<publisher>Prentice Hall</publisher>
</book>
<book isbn="10-90-3467-819" available="yes">
<name>OOSAD using UML</name>
<author>Bennet</author>
<listprice>24.99</listprice>
<price>17.55</price>
<edition>3</edition>
<publisher>Prentice Hall</publisher>
</book>
</books>

Lets create Books.xsl


<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform
" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head><title>Using xsl:if</title></head>
<body>
<h3>Available books in store:</h3>
<table border="1" cellpadding="2"
cellspacing="0">
<tr>
<th>Name</th><th>Author</th><th>
Price</th><th>Edition</th><th>
Publisher</th>
</tr>
<xsl:apply-templates
select="books/book"/>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="book">
<xsl:if test="@available = 'yes'">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="author"/></td>
<td>$<xsl:value-of select="price"/></td>
<td><xsl:value-of select="edition"/></td>
<td><xsl:value-of select="publisher"/></td>
</tr>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Change the xml file as below
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="books.xsl"?>
<books>
.
</books>
The output will be

Available books in store:


Name

Author

Price

Edition

Publisher

SQL ins and


outs

Clerk

$17.55

QUE

OOSAD using
UML

Bennet

$17.55

Prentice
Hall

Look all books are not shown.


Only those books which have available attribute
value equal to Yes are shown.

XML_r15 Page 32

XSL - Conditional Formatting


Saturday, July 14, 2012
9:00 AM

xsl:choose element
xsl:choose allow testing multiple condition
It is like switch case statement in c#
Syntax <xsl:choose>
<xsl:when test="condition 1">
..
</xsl:when>
<xsl:when test="condition 2">
..
</xsl:when>
.
<xsl:otherwise>
...
<xsl:otherwise>
</xsl:choose>
If test ="condition 1" evaluates to true
<xsl:when test="condition 1"> ..</xsl:when> is processed and
proceesing braks out from xsl:choose block
If test ="condition 1" evaluates to false, then test ="condition
2" in the next xsl:when block is tested
If all the xsl:when block fail, <xsl:otherwise></xsl:otherwise>
is processed.
Lets work with another example
Example #7
Lets create books1.xsl as below
Lets create Books.xml
<?xml version="1.0"?>
<books>
<book isbn="10-90-887-909" available="yes">
<name>SQL ins and outs</name>
<author>Clerk</author>
<listprice>24.99</listprice>
<price>17.55</price>
<edition>4</edition>
<publisher>QUE</publisher>
</book>
<book isbn="10-90-3467-819" available="no">
<name>Programming practice</name>
<author>Dave Hart</author>
<listprice>24.99</listprice>
<price>17.55</price>
<edition>4</edition>
<publisher>Prentice Hall</publisher>
</book>
<book isbn="10-90-3467-819" available="yes">
<name>OOSAD using UML</name>
<author>Bennet</author>
<listprice>24.99</listprice>
<price>17.55</price>
<edition>3</edition>
<publisher>Prentice Hall</publisher>
</book>
</books>

XML_r15 Page 33

Lets create books1.xsl


<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transf
orm" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head><title>Using xsl:choose</title></head>
<body>
<h3>book catalog:</h3>
<table border="1" cellpadding="2"
cellspacing="0">
<tr>
<th>Name</th><th>Author</th><th>Price</th>
<th>Edition</th><th>Publisher</th>
</tr>
<xsl:apply-templates select="books/book"/>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="book">
<xsl:choose >
<xsl:when test="@available ='yes'">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="author"/></td>
<td>$<xsl:value-of select="price"/></td>
<td><xsl:value-of select="edition"/></td>
<td><xsl:value-of select="publisher"/></td>
</tr>
</xsl:when>
<xsl:otherwise>
<tr>
<td><s><xsl:value-of select="name"/></s></td>
<td><s><xsl:value-of select="author"/></s>
</td>
<td><s>$<xsl:value-of select="price"/></s></td>
<td><s><xsl:value-of select="edition"/></s>
</td>
<td><s><xsl:value-of select="publisher"/></s>
</td>
</tr>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Output will be
Name

Price

Edition

Publisher

SQL ins Clerk


and outs

Author

$17.55

QUE

Program Dave
ming
Hart
practice

$17.55

Prentice
Hall

OOSAD
using
UML

$17.55

Prentice
Hall

Bennet

xsl:sort
Saturday, July 14, 2012
9:00 AM

Sorting - xsl:sort
xsl:sort is used to specify sort order for node-sets
xsl:sot is used with xsl:apply-templates and xsl:for-each
elements
Syntax:
<xsl:sort select="traineeid" /> - it instructs to a node-set
based tha values of traineeid field, by default sort will in
ascending order
<xsL; sort select="price" data-type="number"
order="descending" /> - it instructs to a node-set based
the values of price field whose data type is number, sort
will in descending order
<xsL; sort select="location" data-type="text"
order="descending" /> - it instructs to a node-set based
the values of location field whose data type is text
Lets work with an example
Example #9
Lets create books2.xml
<?xml version="1.0" ?>
<books>
<book>
<name>XML</name>
<price>240.00</price>
</book>
<book>
<name>HTML</name>
<price>190.00</price>
</book>
<book>
<name>UML</name>
<price>560.00</price>
</book>
<book>
<name>WML</name>
<price>370.00</price>
</book>
<book>
<name>VRML</name>
<price>140.00</price>
</book>
<book>
<name>SGML</name>
<price>340.00</price>
</book>
</books>

<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head><title>Using xsl:sort</title></head>
<body>
<h4>As they are in XML file</h4>
<xsl:for-each select="books/book">
<xsl:value-of select="name"/> - $<xsl:value-of
select="price"/>
<br/>
</xsl:for-each>
<h4>Sorted on name in ascending order:</h4>
<xsl:for-each select = "books/book">
<xsl:sort select="name" data-type="text"
order="ascending"/>
<xsl:value-of select="name" /> $<xsl:value-of select="price" /><br/>
</xsl:for-each>
<h4>Sorted on price in descending order:</h4>
<xsl:for-each select = "books/book">
<xsl:sort select="price" data-type="number"
order="descending"/>
<xsl:value-of select="name" /> $<xsl:value-of select="price" />
<br/>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Change the xml file as below
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="books.xsl"?>
<books>
.
</books>
The output will be

As they are in XML file:


XML - $240.00
HTML - $190.00
UML - $560.00
WML - $370.00
VRML - $140.00
SGML - $340.00

Sorted on name in ascending order:


HTML - $190.00
SGML - $340.00
UML - $560.00
VRML - $140.00
WML - $370.00
XML - $240.00

Sorted on price in descending


order:
UML - $560.00
WML - $370.00
SGML - $340.00
XML - $240.00
HTML - $190.00
VRML - $140.00

XML_r15 Page 34

XML-Data (XSD- Chapter 10


Saturday, July 14, 2012
8:00 AM

Homework:

Today's Topics:

Looks at the table definition

You have to convert the above definition into XSD


schema
Create your own types to apply constrains on the data
Create a sample XML file

Schema
Need for Schema
Goals
Structure of Schema Documents
Workouts
complexType
Elements
Sequence
Attributes
Data Type
Occurrence
simpleType
Restrictions

Important Points:

Lecture Topic:
During the lecture, take notes here. Append extra page(s) if required

XML_r15 Page 35

XML-Data - Schema
Saturday, July 14, 2012
9:00 AM

XML-Data
An specific application of XML
It is used create schema
Schema
A schema identifies the structure and constraints of a
particular XML document
Why use Schema
We used DTD to define structure of our XML documents
There are some limitations
It does not use XML syntax
It does not have rich data type
It does not apply constraints like - data length,
pattern
Primary key , relation are not supported
And that is why we use Schema
XSD - XML Schema Definition
XSD is used to define structure and constraints of XML
Documents
XSD is more powerful than DTD
Writing XSD
To create a XSD, you have to import a URI of schema
namespace http://www.w3.org/2001/XMLSchema
The schema element
Everything in a Schema document must in side the
schema element of W3C's XMLSchema namespace
<?xml version="1.0" ?>
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!-- Schema Definitions Here -->
</xs:schema>
In the schema above we use the standard namespace (xsd),
and the URI associated with this namespace is the Schema
language definition, which has the standard value of
http://www.w3.org/2001/XMLSchema.
Element definitions
To Define an element we use <xsd:element >
<xsd:element name="person" />
Here we defined an element person which have data
type string and string data type is prefixed with xsd
as it is predefined data type in XML Schema
Element can have data type specified by type
attribute
<xsd:element name="person" type="xsd:string" />
[Look how data tyep is specified, we have written
xsd: string. String data type is impoted from
XMLSchema. We will explore all the supported data
type later]
Element cardinality is defined by two attribute
minOccurs - can have an integer value, 0
means the element may not appear. Default
value is 1
maxOccurs - an integer values or unbounded
can be specified. Unbounded means the
element can appear any number of times.
Default value is one
<element name="trainee" minOccurs="0"
maxOcuurs="15" />
The element trainee may not appear or it can
be there 15 times
A element can contain complexType or simpleType

complexType
When a element contains other element(s) or
attribute(s), the element is a complexType
A complexType contains defines allowable elements
sequence
Sequence specifies the order in which elements
appear
choice
Allows elements to choose from a set
simpleType
allows you create your own data type from existing
xsd data types.
Attribute definitions
Attributes similar to elements
Attribute use can controlled using the use attribute in the
attribute definition
use="required" - attribute must appear with an
element
use="optional" - attribute is optional
use="prohibited" -attribute can be specified
Ex: <attribute name="traineeid" type="xsd:string"
use="required" />
Attribute can have default value
<attribute name="location" type="xsd:string"
default="Dhaka" />
Lets work with an example
Book.xsd
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:element name="book">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="title"
type="xsd:string" />
<xsd:element name="price"
type="xsd:decimal" />
</xsd:sequence>
<xsd:attribute name="isbn" type="xsd:string"
use="required" />
</xsd:complexType>
</xsd:element>
</xsd:schema>
Here we defined a an element book, it is the top-level
element
book contains other elements, so it is a complexType
book contains other element in a sequence
name - it is of type string
price - it is of type string
Lets a create sample xml file
Book.xml
<?xml version="1.0"?>
<book xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
xsi:noNamespaceSchemaLocation="book.xsd">
<name>XML</name>
<price>780.00</price>
</book>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
and xsi:noNamespaceSchemaLocation="book.xsd"
These two things are to associate an XSD with xml file
It imports a namespace
"http://www.w3.org/2001/XMLSchema-instance" given a
prefix xsi. xsi:noNamespaceSchemaLocation="xsd file" is
used to point the location and name of the XSD file

XML_r15 Page 36

XSD - Global and Named type


Saturday, July 14, 2012
8:00 AM
Creating Global Type
You can create a global type and refer it to an element
declaration
Lets work with an example
We will recreate the same schema using a global type
Bokk_1.xsd
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:element name="book" type="BookType" />
<xsd:complexType name="BookType">
<xsd:sequence>
<xsd:element name="name"
type="xsd:string" maxOccurs="1"
minOccurs="1"/>

<name>ASP .NET</name>
<publisher>MPress</publisher>
<price>880.00</price>

<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="6"/>

<xs:length value="8"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

This example defines an element called "password" with


a restriction. The value must be minimum five
characters and maximum eight characters

<xsd:simpleType name="nameType">
<xsd:restriction base="xsd:string">
<xsd:maxLength value="20"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:element name="publisher"
type="xsd:string" maxOccurs="1"
minOccurs="1" />
<xsd:element name="price"
type="xsd:decimal" maxOccurs="1"
minOccurs="1" />
</xsd:sequence>
<xsd:attribute name="isbn" type="xsd:string"
use="required"/>
</xsd:complexType>
</xsd:schema>
Here we created a Global Type BookType and then we
defined our element book is type is declared as BookType
Lets validate an XML file
Book_1.xml
<?xml version='1.0' ?>
<book isbn="8890-786-90-92"
xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
xsi:noNamespaceSchemaLocation="book_
1.xsd" >

Ex:

</book>
SimpleType
We use simpleType to create own Data Type
simpleType allows you to create you data type based on the
basic supported data types.
Suppose you want to define an element that will have
content 20 characters long text. You can do this using a
simpleType
You can apply constraints to your data type setting
restrictions
Syntax:
<xsd:simpleType name="a-name">
<xsd:resstriction base="base-type">
<!-- resctriction -->
</xsd:restriction>
</xsd:simpleType>

This example defines an element called "nameType".


The value can have maximum 20 characters

<xsd:simpleType name="isbnType">
<xsd:restriction base="xsd:string">
<xsd:pattern value="[0-9]{6}"/>
</xsd:restriction>
</xsd:simpleType>
This example defines an element called "isbnType". The
value will have 6 digits

<xsd:simpleType name="priceType">
<xsd:restriction base="xsd:decimal">
<xsd:minExclusive value="0"/>
</xsd:restriction>
</xsd:simpleType>
This example defines an element called "priceType".
The value will must be over zero.

Restrictions for Datatypes (not all are listed)


Constraint

Description

enumeration

Defines a list of acceptable values

length

Specifies the exact number of


characters or list items allowed. Must
be equal to or greater than zero

maxExclusive

Specifies the upper bounds for


numeric values (the value must be
less than this value)

maxInclusive

Specifies the upper bounds for


numeric values (the value must be
less than or equal to this value)

maxLength

Specifies the maximum number of


characters or list items allowed. Must
be equal to or greater than zero

minExclusive

Specifies the lower bounds for numeric


values (the value must be greater
than this value)

minInclusive

Specifies the lower bounds for numeric


values (the value must be greater
than or equal to this value)

minLength

Specifies the minimum number of


characters or list items allowed. Must
be equal to or greater than zero

pattern

Defines the exact sequence of


characters that are acceptable

XML_r15 Page 37

XSD - Workout
Saturday, July 14, 2012
8:00 AM
Lets Create a XSD file
namedtypes.xsd
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:simpleType name="nameType">
<xsd:restriction base="xsd:string">
<xsd:maxLength value="20"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="isbnType">
<xsd:restriction base="xsd:string">
<xsd:pattern value="[0-9]{6}"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="priceType">
<xsd:restriction base="xsd:decimal">
<xsd:minExclusive value="0"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:element name="books">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="book" maxOccurs="unbounded" minOccurs="1">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="name" type="nameType" />
<xsd:element name="price" type="priceType"/>
</xsd:sequence>
<xsd:attribute name="isbn" type="isbnType" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Create namedtypes.xml
<?xml version="1.0" ?>
<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="namedtypes.xsd">
<book isbn="898989">
<name>A Tale of Two citie</name>
<price>23.99</price>
</book>
<book isbn="898990">
<name>A Tale of Two cities</name>
<price>27.0</price>
</book>
</books>

Important Notes

XML_r15 Page 38

XSD - Chapter 11 & 13


Saturday, July 14, 2012
8:00 AM

Homework:

Today's Topics:

Looks at the table definition

More on restrictions (cont'd)


XSD Constraints
Unique constraint
Key constraint
keyRef
Workouts

You have to convert the above definition into


XSD schema
Create your own types to apply constrains on
the data
Create a sample XML file
[You have to apply primary-key constraint]

Important Points:

Summary
After the lecture, use this space to summarize the main points of this Lecture Topic.

XML_r15 Page 39

More on Restrictions
Saturday, July 14, 2012
8:00 AM
Restrictions are used to define acceptable values for XML elements or
attributes.
Restrictions on Values
The following example defines an element called "age" with a
restriction. The value of age cannot be lower than 0 or greater than
120:
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="120"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Restrictions on a Set of Values
To limit the content of an XML element to a set of acceptable values,
we would use the enumeration constraint.
The example below defines an element called "car" with a restriction.
The only acceptable values are: Audi, Golf, BMW:
<xs:element name="car">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Audi"/>
<xs:enumeration value="Golf"/>
<xs:enumeration value="BMW"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Other Restrictions on a Series of Values
The example below defines an element called "letter" with a
restriction. The acceptable value is zero or more occurrences of
lowercase letters from a to z:
<xs:element name="letter">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="([a-z])*"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
The next example also defines an element called "letter" with a
restriction. The acceptable value is one or more pairs of letters, each
pair consisting of a lower case letter followed by an upper case letter.
For example, "sToP" will be validated by this pattern, but not "Stop" or
"STOP" or "stop":
<xs:element name="letter">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="([a-z][A-Z])+"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
The next example defines an element called "gender" with a restriction.
The only acceptable value is male OR female:
<xs:element name="gender">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="male|female"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
The next example defines an element called "password" with a
restriction. There must be exactly eight characters in a row and those
characters must be lowercase or uppercase letters from a to z, or a
number from 0 to 9:

<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[a-zA-Z0-9]{8}"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Restrictions on Length
To limit the length of a value in an element, we would use the
length, maxLength, and minLength constraints.
This example defines an element called "password" with a
restriction. The value must be exactly eight characters:
<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:length value="8"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
This example defines another element called "password" with
a restriction. The value must be minimum five characters and
maximum eight characters:
<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="5"/>
<xs:maxLength value="8"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
XSD Constraints
XSD allows allow you to define contains on elements/attributes
Also allows you to implement relations amongst elements or
attributes
Unique
XSD allows describing uniqueness constraints
The following declaration done under the declaration of our
book element indicates that the ISBN must be unique:
<xs:unique name="charName">
<xs:selector xpath="book"/>
<xs:field xpath="@ISBN"/>
</xs:unique>
<xs:selector xpath="book"/> - describes the node to which the
uniqueness apply (relative to context node). The node must be
an element node
<xs:field xpath="@ISBN"/This is the node whose value will be
checked for uniqueness. The node can be an element or an
attribute node.
Key
he key constraint acts same as unique constraint. But key
allows null but unique does not
To use the ISBN as a key, we can just replace the xs:unique by
xs:key:
<xs:key name="charName">
<xs:selector xpath="character"/>
<xs:field xpath="name"/>
</xs:key>
Keyref
The third construct, xs:keyref, allows us to define a reference
to a xs:key or a xs:unique.
It allows to create relationship like RDBMS
<character>
<name>Snoopy</name>
<friend-of>Peppermint Patty</friend-of>
<since>1950-10-04</since>
<qualification>
extroverted beagle
</qualification>
</character>

XML_r15 Page 40

XSD Constraints
Saturday, July 14, 2012
8:00 AM
To indicate that friend-of needs to refer to a character from
this same book, we will write, at the same level as we defined
our key constraint, the following:
<xs:keyref name="charNameRef" refer="charName">
<xs:selector xpath="character"/>
<xs:field xpath="friend-of"/>
</xs:keyref>
Some examples
The "xpath" attribute of "selector" and "field" elements is a
restricted XPath relative to the element in which it is declared
(here it is relative to the "root" element).
#1
Ex_0.xsd
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:element name="root" >
<xsd:complexType>
<xsd:sequence minOccurs="1">
<xsd:element name="a" minOccurs="1"
maxOccurs="unbounded">
<xsd:complexType>
<xsd:attribute name="id"
type="xsd:NCName"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
<xsd:unique name="myId">
<xsd:selector xpath="./a"/>
<xsd:field xpath="@id"/>
</xsd:unique>
</xsd:element>
</xsd:schema>
Valid document
<root xsi:noNamespaceSchemaLocation="Ex_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<a id="x"/>
<a id="y"/>
<a id="z"/>
</root>
#2
Ex_1.xsd
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:element name="root">
<xsd:complexType>
<xsd:sequence minOccurs="1" maxOccurs="1">
<xsd:element name="AAA">
<xsd:complexType>
<xsd:sequence minOccurs="1">
<xsd:element name="a"
minOccurs="1"
maxOccurs="unbounded">
<xsd:complexType>
<xsd:attribute name="id"
type="xsd:NCName" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>

<xsd:element name="BBB">
<xsd:complexType>
<xsd:sequence minOccurs="1">
<xsd:element name="b"
minOccurs="1"
maxOccurs="unbounded">
<xsd:complexType>
<xsd:attribute name="idref"
type="xsd:NCName" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
<xsd:key name="myId">
<xsd:selector xpath="./AAA/a"/>
<xsd:field xpath="@id"/>
</xsd:key>
<xsd:keyref name="myIdref" refer="myId">
<xsd:selector xpath="./BBB/b"/>
<xsd:field xpath="@idref"/>
</xsd:keyref>
</xsd:element>
</xsd:schema>
<root
xsi:noNamespaceSchemaLocation="correct_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<AAA>
<a id="x"/>
<a id="y"/>
</AAA>
<BBB>
<b idref="x"/>
<b idref="y"/>
<b idref="y"/>
</BBB>
</root>

Lets work with an example


Unique.xsd
<?xml version='1.0'?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:element name="books">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="book"
type="bookType" minOccurs="1"
maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:unique name="myId">
<xsd:selector xpath="book"/>
<xsd:field xpath="id"/>
</xsd:unique>
</xsd:element>
<xsd:complexType name="bookType">
<xsd:sequence minOccurs="1">
<xsd:element name="id" type="xsd:string"/>
<xsd:element name="name" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
You must define unique/key/keyRef constraints within root
element

XML_r15 Page 41

XSD Constraints

Relation.xml
<publications
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="relation.xsd">
<authors>
<author>
<auid>au001</auid>
<name>Bell</name>
</author>
<author>
<auid>au002</auid>
<name>Kim</name>
</author>
</authors>
<books>
<book auref="au001">
<name>SQL</name>
<price>290</price>
</book>
<book auref="au001">
<name>SQL</name>
<price>290</price>
</book>
</books>
</publications>

Saturday, July 14, 2012


8:00 AM
Book.xml
<?xml version="1.0" ?>
<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="unique.xsd">
<book>
<id>a001</id>
<name>Habib</name>
</book>
<book>
<id>a002</id>
<name>Habib</name>
</book>
</books>
Lets work with another example
relation.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:element name="publications">
<xsd:complexType>
<xsd:sequence minOccurs="1" maxOccurs="1">
<xsd:element name="authors" type="authorsType" maxOccurs="1"
minOccurs="1"/>
<xsd:element name="books" type="booksType" maxOccurs="1"
minOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
<xsd:key name="aukey">
<xsd:selector xpath="./authors/author"/>
<xsd:field xpath="auid"/>
</xsd:key>
<xsd:keyref name="aukeyref" refer="aukey">
<xsd:selector xpath="./books/book"/>
<xsd:field xpath="@auref"/>
</xsd:keyref>
</xsd:element>

A problem
Look at Products table

<xsd:complexType name="authorsType">
<xsd:sequence minOccurs="1">
<xsd:element name="author" minOccurs="1"
maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="auid" type="xsd:string"
maxOccurs="1" minOccurs="1" />
<xsd:element name="name"
type="xsd:string" maxOccurs="1" minOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="booksType">
<xsd:sequence minOccurs="1">
<xsd:element name="book" minOccurs="1" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="name" type="xsd:string" />
<xsd:element name="price" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="auref" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>

XML_r15 Page 42

Column Name Data


Type
productid

char

productname

varchar

price

Decimal

Length

Convert it into XSD Schema.

Other Constraints
4 value follows a
pattern, starts with
"P-" then two digits
like P-01, P-02 and it
is primary key
30
must be over zero

XML-Data (XML Schema Document) -Chapter 10


Saturday, July 14, 2012
8:00 AM

Homework:

Today's Topics:
What is XML Schema Document
Need for it
XML Schema Document Structure
ElementType
AttributeType
element
attribute
Workouts

Important Points:

Lecture Topic:
During the lecture, take notes here. Append extra page(s) if required

XML_r15 Page 43

XML Schema
Saturday, July 14, 2012
8:00 AM

XML Schema
It is a language to express the structure and
constraints of a particular XML Document.
It is a Microsoft terminology
It is Microsoft's first effort to improve weaknesses of
DTD [W3C Schema is now different and Microsoft
currently implementing W3C's XSD]
Schema Document Structure
XML Schema Document Structure
The following are the elements of a Schema document
Schema - Serves the root element for XML Schema
Document
datatype - describes the data types for elements and
attribute
ElementType - Describes a type of element
element - defines an element that appears within
another ElementType
group - organizes elements in a group in order
AttributeType - defines a type of attribute
attribute - defines an attribute that appears within
another AttributeType
[ElementType, AttributeType are to-level element in
XML Schema document. They appear directly under
the root Schema. Look all start with Capital Letter. All
the except these are local-level and they appear within
other to-level elements]
The Schema Element
It servers as the root element of an XML Schema
document.
It has two attributes
name - the name of the schema
namespace (xmlns) - the namespace for the
Schema. It must be set to "urn:schemasmicrosift-con:xml-data"
Example:
<Schema name="MySchema" xmlns="urn:schemasmicrosift-con:xml-data">
<!-- content goes here -->
</Schema>
In order to use XML Schema dat type like date,
time, int, float and so on you import another
namespace "urn:schemas-microsiftcon:datatypes"
<Schema name="MySchema" xmlns="urn:schemasmicrosift-con:xml-data" xmlns:dt="urn:schemasmicrosift-con:datatypes">
<!-- content goes here -->
</Schema>
The datatype element
dataype element is used to set data type for an
element or attribute.
It is set using dt:type attribute. Ex.: dt:type="float"
[See book appendix for full list of supported data
type ]

The ElementType Element


The ElementType element is used to define
element types
It has the following attribute
name -the name of the element
model - specifies whether the content model
open or closed
open - allows additional element to be
included with the ElementType that
are not defined in the Schema
closed - does not allows to include
additional element
Default is open
content - the type of content within the element
empty - the element does not contain any
content
textOnly - only contains text
eltOnly - only elemnts as cild allowed
mixed - mixture of text and elements is
allowed
order - the order of the child elements and groups
one - only one set of elements is allowed
seq - elements must appear in in sequence
many - element may appear many times in
any order
dt:datatype - the data type of an element
The element type can contains elements,
attributes - these are local-level Schema elements
as they appear within other top-level elements
The element Element
It is used to declare an element within an
ElementType or group
type - the type of element defined by an
ElemetType
minOccurs the minimum number time the
element must occur. Zero (0) means the
elemet optional
maxOccurs - the maximum number times
the element can appear. * means the
element can appear any number of time.
The group Element
It allows you to organize elements in groups
order - the order of child elements
one - only one set of elements is
allowed
seq - elements must appear in in
sequence
many - element may appear many
times in any order
minOccurs the minimum number time the
element must occur. Zero (0) means the
elemet optional
maxOccurs - the maximum number times
the element can appear. * means the
element can appear any number of time.

XML_r15 Page 44

XML-Data (XML Schema Document)


Saturday, July 14, 2012
8:00 AM

The AttributeType Element


It is used define attribute type for use in in elements
name - the name of the attribute
dt:type - the data type for the attribute
dt:values - list of possible values of an attribute
default - the default value
required - the flag indicating the attribute must be
provided
The attribute Element
It is used to define an attribute
type - the type of attribute
default - the default value
required - the flag indicating the attribute must be
provided
Lets play with some example
BookScema.xml
<?xml version='1.0' ?>
<Schema name="BookSchema" xmlns="urn:schemasmicrosoft-com:xml-data"
xmlns:dt="urn:schemas-microsoft-com:datatypes">
<ElementType name="name" dt:type="string"/>
<ElementType name="price" dt:type="float"/>
<AttributeType name="genre"
dt:type="enumeration" dt:values="Classics
Autobigraphy Others" default="Others"/>
<ElementType name="book" content="eltOnly"
order="seq">
<element type="name" minOccurs="1"
maxOccurs="1" />
<element type="price" minOccurs="1"
maxOccurs="1" />
<attribute type="genre"/>
</ElementType>
</Schema>
The Document has the root element <Schema .>
</Schema>
We declared three top-level Schema element
<ElementType name="name" dt:type="string"/>
An ElementType with name "name" and it has
string content
<ElementType name="price" dt:type="float"/>
An ElementType with name "price" and it has float
data (numeric) content
<AttributeType name="genre"
dt:type="enumeration" dt:values="Classics
Autobigraphy Others" default="Others"/>
An AttributeType with name "genre" which can
have one of values - Classics, Autobiography or
others. The default value is Others.

Now come to
<ElementType name="book" content="eltOnly"
order="seq">
<element type="name" minOccurs="1"
maxOccurs="1" />
<element type="price" minOccurs="1"
maxOccurs="1" />
<attribute type="genre"/>
</ElementType>
It declares an ElementType named book which
can contain only elements and elements must be
in order they are declared
<element type="name" minOccurs="1"
maxOccurs="1" /> an element of type "name" as
define by the
<ElementType name="name" dt:type="string"/>
name lement can appear once and only once
<attribute type="genre"/> an attribute named
genre defined by
<AttributeType name="genre"
dt:type="enumeration" dt:values="Classics
Autobigraphy Others" default="Others"/>
Now create an Sample XML file to validate with
the Schema
Book.xml
<?xml version='1.0' ?>
<book genre="Classics" xmlns="xschema:BookSchema.xml">
<name>All Quiet on the Western
Front</name>
<price>700.99</price>
</book>
Look how we associate the XML file with the
Schema
<book genre="Classics" xmlns="xschema:BookSchema.xml">
xmlns="x-schema:BookSchema.xml" actually
associates the Schema document with XML file
It must be within the root element in the XML
file

XML_r15 Page 45

XML-Data (XML Schema Document)


Saturday, July 14, 2012
8:00 AM

Lets work with another example


BooksSchema.xml
<Schema name="BookSchema" xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:dt="urn:schemas-microsoft-com:datatypes">
<ElementType name="name" content="textOnly" />
<ElementType name="price" dt:type="float"/>
<AttributeType name="genre" dt:type="enumeration" dt:values="Classics Autobigraphy Others"
default="Others"/>
<AttributeType name="id" dt:type="id" />
<ElementType name="book" content="eltOnly" order="seq">
<element type="name" minOccurs="1" maxOccurs="1" />
<element type="price" minOccurs="1" maxOccurs="1" />
<attribute type="genre"/>
<attribute type="id"/>
</ElementType>
<ElementType name="books" content="eltOnly">
<element type="book" minOccurs="1" maxOccurs="*" />
</ElementType>
</Schema>
Lets create a Sample XML to validate
Books.xml
<?xml version='1.0' ?>
<books xmlns="x-schema:BooksSchema.xml">
<book id="B-01" genre="Classics">
<name>All Quiet on the Western Front</name>
<price>700.99</price>
</book>
<book id="B-02">
<name>The Hundred</name>
<price>1999.99</price>
</book>
</books>

Important Points:

XML_r15 Page 46

Anda mungkin juga menyukai