Вы находитесь на странице: 1из 67

EXtensible Markup Language

©NIIT eXtensible Markup Language 1


2 eXtensible Markup Language ©NIIT
RATIONALE

Why This Module


Data interchange is essential to carry out business transactions. The challenge in carrying out data
interchange lies in establishing standard interfaces among enterprises with related business interests or
groups within an enterprise, in which the data is stored in disparate forms. XML provides a structure for
storing data in text format, which can be used as a standard format or protocol for data interchange. It
plays an extended role as a very robust data interchange format which is essential for various
applications.
XML allows creation of custom markup tags, thereby providing flexibility to define structure of the
content and also describe the content. This flexibility of XML has enabled chemical, cellular, mobile,
and many more industries to describe and define the content according to their requirements. Chemical
Markup language, Wireless Markup Language, Math Markup Language are examples of industry
specific markup languages developed using XML. They allow definition and description of industry
specific data. For example, molecules, atoms, and elements can all now be defined and described using
the Chemical Markup Language. Similarly, complex mathematical equations, such as calculations, can
be represented using Math Markup languages. SMIL is one such markup language, which allows
integration of media such as audio and video into Web pages. Thus, XML serves as an enabling
technology for many other technologies.

XML stores data in device-independent format. XML documents can be exchanged over the Web. This
enables usage of XML for all e-commerce transactions on the Web. ebXML is the latest XML-based
markup language aiming to define and develop standards for electronic business and data exchange
between businesses on the Web.

Software programs, applications, and environments, such as Microsoft Office XP and Microsoft .Net
framework, support XML extensively. In addition, relational database management systems such as
SQL Server 2000 allow generation of XML documents. Software giants like IBM, Oracle and Sun
Microsystems are also integrating their products with XML. Therefore, XML is fast emerging as a
standard technology to describe and define documents.

In this module, students will be introduced to the features of XML and its advantages over traditional
electronic data interchange (EDI). Students will also learn about various XML-related specifications,
such as Document Type Definitions, XML schemas, eXtensible Style Sheet Language Transformations
(XSLT), XPath, XML Document Object Model, and Xlink and XPointer. During this module, students
will learn to create well-formed and valid XML documents. They will also learn to format XML
documents by using Cascading Style Sheets (CSS) and XSLT. Then, they will learn to access various
parts of an XML document through JavaScript by using XML Document Object Model.

©NIIT eXtensible Markup Language 3


OBJECTIVES
Besides introducing students to the fundamentals of XML, this module will familiarize them with the
following:

„Using XML as a standard data interchange format

„Creating a well-formed XML document

„Creating Document Type Definitions (DTD) and XML schemas for ensuring the consistency in the
structure of XML documents

„Using namespaces in XML documents for avoiding conflicting element names

„Formatting XML documents by using style sheets

x Cascading Style Sheets (CSS)

x eXtensible Style Sheet Language Transformations (XSLT)

„Using Xpath patterns and functions for querying XML documents

„Accessing different parts of an XML document by using XML Document Object Model (DOM)

At the end of the XML module, the student should be comfortable with the basic concepts of XML and
also be able to effectively use XML as a markup language to develop Web applications.

4 eXtensible Markup Language ©NIIT


ENTRY PROFILE
A student who registers for the XML module should be able to perform the following tasks:

„Create Web pages by using HTML

„Write code in JavaScript for handling various events

„Identify features of OOP

„Work in Windows environment

„Create and maintain documents by using an editor and perform simple editing tasks

„Interact in English in a classroom environment

©NIIT eXtensible Markup Language 5


EXIT PROFILE
At the end of this module, the student will be able to:

„Design XML documents

„Define schemas and validation rules for XML documents using the DTD and XSD languages

„Write stylesheet programs to transform the data present in an XML document

„Write programs using JavaScript and DOM to access XML documents

Skills Acquired
„Create well-formed XML documents

„Use DTD to define XML documents

„Create XML documents and validate them against the DTD

„Use XSD to define XML documents

„Create XML documents and validate them against the schema

„Use XSL to transform XML documents and present the data in the Web browser

„Use JavaScript and DOM to access and manipulate data present in an XML document

6 eXtensible Markup Language ©NIIT


FAQ
1. What is XML?

Extensible Markup Language (XML) is a way of structuring data on the Web. Using XML, you can
create your own markup language. HTML concentrates on the presentation of data on the Web. For
example, when you use the <P> tag of HTML, the browser interprets it as a paragraph and displays
the text within the tags accordingly. XML, on the other hand, does not have any predefined tags.
XML concentrates on the content within the tags. For example, for representing customer
information, you can create your own tag, <CUSTOMER>. XML is a text-based format that lets
developers describe, deliver, and exchange data between different applications. It is a database- and
device-neutral format. It stores data in a structured text format, which can be easily used by any
computerized system. XML supports UNICODE as well and hence will help internationalize the
World Wide Web.

2. Who invented XML?

XML is designed by a working group of the World Wide Web Consortium (W3C), which is an
organization that aims at leading the WWW to its full potential by developing common protocols
that promote the World Wide Web and ensure its interoperability. The XML development effort
started in 1996 led by Jon Bosak of Sun Microsystems. Bosak organized a diverse group of markup
language experts, from industry to academia, to develop a simplified version of SGML (Standard
Generalized Markup Language) for the Web. In February 1998, XML 1.0 specification became a
recommendation by the W3C.

Today, the XML Working Group consists of 14 companies and organizations, including Adobe,
ArborText, DataChannel, Fuji Xerox, Hewlett-Packard, Inso, Isogen, Microsoft, Netscape,
SoftQuad, and Sun Microsystems.

3. Will XML replace HTML?

No. XML is not going to replace anything that you have learned. XML complements it. You can
use XML to create your own tags and then use HTML tags to format the data in XML document.
You can use Cascading Style Sheets to define the font colors and the position of text within the tags
in an XML document.

4. What are the XML-related specifications?

XML is defined by the following specifications:

XML 1.0 defines the syntax of XML.

XML Pointer Language (XPointer) and XML Linking Language (XLink) define the standard way
of representing links between various resources.

Extensible Style Sheet language (XSL) defines the style sheet language for XML.

The specifications for namespaces, XML Query Language, and XML Schema are being actively
pursued.

5. What are the key benefits of XML?

XML simplifies data interchange. It also reduces the cost involved in interchanging data between
different applications. It is a plain text format that can be understood by different software and
hardware platforms. Therefore, you do not require any special software for reading XML data.
XML is flexible and extensible, unlike traditional EDI, which had rigid transaction sets. XML

©NIIT eXtensible Markup Language 7


allows you to easily introduce new tags and thereby create structured documents based on business
requirements. XML also provides support for Unicode. This feature allows you to create
applications that provide global language support.

6. What are the applications of XML?


XML is poised to play a prominent role as a data interchange format in electronic business Web
applications such as e-commerce, supply-chain management, and application integration. Another
use of XML is for structured information management, including information from databases.
XML also supports media-independent publishing, allowing documents to be written once and
published in multiple media formats and devices. On the client side, XML can be used to create
customized views of data based on user requirements. In case of the middle layer, XML is fast
emerging as a standard data interchange format between applications and various components. For
example, Microsoft .Net framework has introduced Web services, which use XML for
communication with the client application. A Web service is a piece of code that can be accessed
by using Internet protocols, such as the Hypertext Transfer Protocol (HTTP). A Web service is
similar to a component, which provides some functionality that can be accessed without knowing
about its implementation. However, components have a limitation. They use object-model specific
protocols, such as Internet Inter-ORB Protocol (IIOP) and Remote Method Invocations (RMI), for
communication. As against this, a Web service uses standard Internet protocols such as HTTP and
standard data formats such as eXtensible Markup Language (XML) for communication over the
Internet.

7. What is the relationship between XML and the Java technology?

XML and the Java technology are complementary. Java is a platform-independent programming
language and XML is a platform-independent data interchange format. Java provides the portable,
maintainable code to process portable, reusable XML data. In addition, XML and Java have a
number of shared features that make them the ideal pair for Web computing, including being
industry standards, platform-independent, extensible, reusable, Web-centric, and internationalized.

8. What are the benefits of using the Java technology with XML?

The Java technology offers a substantial productivity boost for software developers compared to
programming languages such as C or C++. In addition, developers using the Java platform can
create sophisticated programs that are reusable and maintainable across diverse software and
hardware platforms compared to programs written with scripting languages. Using XML and Java
together, developers can build sophisticated, interoperable Web applications more quickly and at a
lower cost.

9. What XML technologies are being developed for the Java platform?

Sun is actively involved in delivering first-class XML support in the Java platform. Through the
Java Community Process, two initiatives are in progress: a Java optional package for XML parsing
and XML data binding, a project codenamed "Adelard." XML is also used in Java 2 Enterprise
Edition (J2EE) as an essential means of information interchange in disparate business systems.

10. What XML-related activities is Sun participating in?

Sun is actively participating in W3C working groups for eXtensible Style Sheet Language
Transformation (XSLT), XML Schema, XLink, and XML Query. Sun is also participating in a
number of other industry consortia including OASIS, XML.org, and Apache. See Sun's XML home
page (http://java.sun.com/xml/) for complete information.

11. What is Java API for XML Parsing?

The Java API for XML Parsing provides basic functionality for reading, manipulating, and
generating XML documents through pure Java Application Programming Interfaces (API). It is a
simple API that provides a standard way for any XML conformant parser to be accessed by an

8 eXtensible Markup Language ©NIIT


application. Using this software, application and tools developers can build fully functional XML-
enabled Java applications for e-commerce, application integration, and Web publishing.

12. What Java runtime environment is required to run the software?

The XML Parsing API will run in both JDK 1.1.8 and the Java 2 platform.

13. Is this software compliant with Java Project X?

Yes. The JAXP reference implementation (RI) uses the high performance Java Project X as its
default parser.

14. What is Java Project X?

Java Project X is an experimental technology that provides core XML services written for reading,
manipulating and generating XML data. This package features an extremely fast validating and
non-validating XML parser that is fully compliant to the W3C XML 1.0 recommendation, SAX
1.0, DOM Level 1 Core, and XML Namespaces. Project X is available for commercial
redistribution and can be downloaded from http://java.sun.com/xml/xml-side1.html.

15. Are there any certifications for XML?


Yes. IBM provides certification for XML and related technologies (Test 140). A sample test for this
certification is provided at the IBM site, http://www-4.ibm.com/software/ad/certify/sam140.html
For more information refer to the site www.ibm.com.

16. What are the pre-requisites for appearing for this certification?

This certification recommends the following pre-requisites:


„Experience in designing and implementing computer applications.
„Background in programming/scripting and understanding of basic computer science models
and data structures. In particular, familiarity with XML related computer science concepts like
tree traversal, recursion, and reuse of data.
„Familiarity with Internet standards and concepts (e.g., Web Browser, client-server, relational
databases, documenting, formatting, e-commerce).

17. How will this certification help me?

The certification would help you to design and implement applications that make use of XML. It
ensures a strong understanding of XML fundamentals and a broad knowledge of XML concepts
and related technologies. It also helps in understanding how data relates to XML, in particular with
issues associated to information modeling, XML processing, XML rendering, and XML query with
a thorough knowledge of core XML related W3C recommendations and is familiar with well-
known best practices.

18. Where can I take this exam?

This exam can be taken at any one of the authorized Sylvan Prometric Centre spread worldwide.

©NIIT eXtensible Markup Language 9


LESSON SPECIFIC INPUTS
The codes for demos, just a minutes, guided practices, and unguided practices for various lessons are
stored under the respective folders in the Data Files folder of the TRM CD. The names of files to be
used for each demo/practice are specified at the beginning of each code in the CG.

Lesson One
Experiences
You can start this session by explaining the need for data interchange and how it affects various
applications. As an example, you can discuss B2B e-commerce scenario, where two business partners
need to interchange data. Then, introduce electronic data interchange (EDI) and then discuss XML and
its role in electronic data interchange in modern applications.

You can start the demo section of the lesson by first talking about the information that must be
contained in an XML document for the given scenario. You can then explain the various components
that make up an XML document. Students must have a very clear understanding of what these
components are and how they are used. Next, you can organize the data to be stored as elements,
attributes and so on. Finally, the students can be shown the code that is the solution for the given
scenario.

Please explain each advantage of using XML with an example. This will make it easier for the student
to understand the difference between HTML and XML.
In the Verify the Solution part of 1.D.1, stress the fact that since XML does not deal with presentation,
the data will be displayed along with tags unlike in the case of HTML, where the data was formatted on
the basis of the tags used. Tell the students not to bother about the ‘look’ of the data. Just tell them that
they will be learning some tools to display formatted data in subsequent sessions.
Students should be made to understand the rules that are specified for a well-formed XML document.
You can also give them small code snippets and tell students to identify whether the document is well-
formed. If the code snippet is not well-formed, ask students to state the reason.

Examples and Analogies


While explaining the structure and basic components of an XML document , you can use a simple real-
life scenario. This scenario can be based on a conversation between an employer and an employee or
between a student and a teacher to enable the student to understand the logical manner in which data is
organized in an XML document.

You can also compare the syntax and general structure of an XML document with that of an HTML
document. For comparing the syntax, you can take a simple example of a letter and write the code in
HTML. Then, write the same code by using XML to bring out the difference.

While specifying the difference between

While explaining internal entities, you can give an example where an attribute should contain the value
The name of this book is “If Tomorrow Comes”. In this case, the attribute value
contains double quotes embedded within it. To assign this value to an attribute, you would write the
following statement:
<BOOK DESCRIPTION=“The name of this book is &quot;If Tomorrow
Comes&quote;”>

10 eXtensible Markup Language ©NIIT


<AUTHOR> Sydney Sheldon </AUTHOR>
</BOOK>
Inform the students that details about different types of entities are covered in depth in the appendix.
However, to be able to understand how to use the different types of entities, students need to know
about DTDs.

Additional Inputs
In addition to specifying the version and encoding scheme being used in the XML document, the
processing instruction also allows you to specify whether it uses a DTD or not. This is done by using the
“standalone” property of the processing instruction. If you set the “standalone” property of the XML
document to “yes”, it indicates that the XML document either uses an internal DTD or does not use a
DTD at all. If you set the “standalone” property to “no”, it indicates that the XML document uses an
external DTD. For more information on internal and external DTDs, refer to Lesson 2 of the Student
Guide.

FAQ
1. Will the XML document produce the correct output even if the PI for the document is
missing.?

Yes. The PI is optional.

2. Can the output of an XML document be displayed without a browser ?

Yes. You can create an application that displays the output of the XML document in various
formats such as message boxes. You can use XML Document Object Model (DOM) for doing so.
You will learn about XML DOM in lesson 7 and 8.

3. What are the applications for which XML can be used?

XML is set to play an important role as a data interchange format in electronic business Web
applications such as e-commerce and application integration. Another use of XML is for managing
structured data, including information from databases. On the client side, XML can be used to
create customized views to display data.

Problem-wise Inputs
1.D.1.
To execute this demo, open the 1_D_1.xml file in the browser and demonstrate the tree structure of the
XML document.

Solutions: Guided Practice


1.P.1.

1_P_1.xml
<?xml version="1.0"?>
<BOOKDETAILS>
<BOOK BOOKID="B001">
<TITLE>Morning, Noon, and Night</TITLE>
<AUFNAME> Sydney </AUFNAME>
<AULNAME>Sheldon</AULNAME>
<PRICE>10.00</PRICE>
</BOOK>
</BOOKDETAILS>

©NIIT eXtensible Markup Language 11


Lesson Two
Experiences
You can start this session by talking about the need to ensure consistency of the structure of data while
carrying out data interchange. Then, move on to briefly explain how Document Type Definition (DTD)
can be used for ensuring consistency of the structure of data. You can then differentiate between a well-
formed XML document and a valid XML document, thereby bringing out the importance of DTD.

Based on the CyberShoppe scenario, the students must be taught to identify the elements required for
storing structured data. The three different types of element content can be explained by using a sample
code snippet with all the three types of element content.

While explaining how to identify elements and attributes, explain that elements map to nouns and
attributes map to adjectives. Bring out the relationship between the two sets to help students understand
the concept better.

Elements can be declared in the DTD using the <!ELEMENT> statement and attributes can be declared
using the<!ATTLIST> statement. Explain the usage of the different symbols that can be used while
declaring elements. A situation can be given to students and an exercise on how to use these symbols in
the DTD.

Inform the students that they can create DTD files by using any text editor, such as Notepad or Editpad.
The DTD file should be saved with the dtd extension.

The two types of DTD can be explained with a single example, so that students will be able to
understand the difference between the two types of DTD. The <!DOCTYPE> declaration can be
explained in this context.

Explain the concept of parsers before explaining the two types of parsers. Give examples for each type
of parser.

While explaining schemas, state that schemas provide much more control over the type of data that can
be stored in elements and attributes in an XML document. Therefore, schemas are being preferred over
DTDs in current applications.

Examples and Analogies


While explaining the concept of DTD, you can compare it with creating a table in a database.

Creating a DTD is similar to creating a table in a database. In DTDs, you specify the structure of data by
declaring elements to denote the data. This is similar to creating columns in a table. You can also
specify whether providing a value for the element is mandatory or optional. You can then store the data
in an XML document that conforms to the DTD for that application. This is similar to adding records in
a table.

Problem-wise Inputs
2.D.1
Before you execute this demo, ensure that the Learning Environment folder that is required to
validate an XML document against the DTD and a schema is in place. Also ensure that this folder is
copied to all student nodes. The files required for this demo are stored as 2_D_1.dtd and 2_D_1.xml.
To demonstrate the validation process, open validator.htm in Internet Explorer 5.0 and enter the name
of the XML document as 2_D_1.xml. Then, click the Validate link. To demonstrate the types of errors
generated if the XML document does not conform to the schema, delete one of the elements from the
XML document and run the script in validator.htm again. Let the students notice the type of error
generated. Also instruct the students that they must save their documents and the validator.htm script

12 eXtensible Markup Language ©NIIT


in the same folder. If these files are not in the same folder, tell them to ensure that they specify the full
path of the DTD in the XML document.

2.D.2
To demonstrate the validation of an XML document against a schema, use the Schema Validator. You
can do so by opening the index.htm file in IE 5.0 or later. The index.htm file is located in the Learning
Environment folder. Click the Schema Validator link. In the resulting form, enter the name of the XML
document as 2_D_2.xml. Specify the schema name as 2_D_2.xsd. If the schema does not work
properly, the easiest way to find out the problem is by saving the XSD file as an XML document and
opening it in the browser. Check whether your XSD schema is well-formed. More than half of the errors
can be eliminated by checking whether the schema document is well-formed. If the Schema Validator
gives an error stating “Object Required”, please check whether the path specified for the XML
file is correct.

Additional Inputs
You can add a Browse button to the Learning Environment. You can write a script for allowing
students to select a file from the File Open dialog box, instead of making students type the complete
path. For example, if you want to include the Browse button in the DTD validator, open DTD.htm in
Notepad. This file is located in the Learning Environment folder. Add the following code within the
<FORM> and </FORM> tags to add a button to the form.
<input type=“button” onclick=“vbscript:FileOpen()” value=“BROWSE…”>
Now, add the following script within the <HEAD> and </HEAD> tags:
<script language="vbscript">
sub openfile
On Error Resume Next
Dim CDObj
Set CDObj = CreateObject("MSComDlg.CommonDialog")
If Err Then
MsgBox "Can't create Dialog Object!"
End If
CDObj.MaxFileSize = 260 ' Init buffer (NECESSARY!)
CDObj.Flags = &H1004 ' File Must Exist + no ReadOnly checkbox
CDObj.ShowOpen
Dim fname
fname = CDObj.filename
' Cancel or no file name?
If fname <> vbNullString Then
document.frmTransform.txtXMLFileName=fname
End if
document.frmTransform.txtXMLFileName.value=fname
msgbox fname
Set CDObj = Nothing
end sub
</script>

In the above code, the CommonDialog ActiveX control is used. The CreateObject() method of VBScript
is used to create an instance of the CommonDialog control. The ShowOpen() method of this file is used
to display the File Open dialog box. When a user selects a file name, the selected filename is assigned to
the text box in the form. However, the successful execution of the above code depends on the existence
of the comdlg32.dll file on a computer.

©NIIT eXtensible Markup Language 13


FAQ
1. Can I specify a set of predefined values in an IMPLIED attribute?

No. You cannot specify a set of predefined values in an IMPLIED attribute.

2. What is the difference between REQUIRED and IMPLIED attributes?

The main difference between REQUIRED and IMPLIED attributes is that, REQUIRED attributes
must be specified each time the element is used whereas IMPLIED attributes are optional.

3. Can I set a default value for an enumerated value type?

Yes. You can set a default value for an enumerated value type. Consider the following example.

<!ATTLIST PRODUCT CATEGORY (Toy | Book) “Book”>

In the above example, an attribute called CATEGORY is created for the PRODUCT element. The
valid values for this attribute are specified as Toy or Book. The default value of this attribute has
been set to Book.

4. What is the difference between the * and + symbol that can be used while defining the DTD?

If an * symbol is used, an element can occur zero or multiple times. On the other hand, if a +
symbol is used an element must occur at least once.

5. Can I specify the <!ATTLIST> element anywhere in the DTD or it must necessarily follow the
appropriate element declaration?

No. You can use the <!ATTLIST> element anywhere in the DTD. But be sure that you use the
correct element name.

6. Can I have more than one ID type of attributes specified for an element in a DTD?
No. You cannot define multiple ID attributes on the same element.

Solutions: Just a Minute…


1. The branches of CyberShoppe send information about books sold by them to the head office. The
book details must be stored in a consistent format. Restrictions must be placed on the kind of data
that can be saved in the data store to ensure uniformity and consistency of information. The details
of books sold by CyberShoppe consist of the name of the book, ISBN of the book, first and last
names of the author of the book, and the price of the book. Create a DTD for declaring the elements
to be used for storing book details in an XML document.
2_JAM_1.dtd
<!ELEMENT BOOKDETAILS (BOOK)+>
<!ELEMENT BOOK (TITLE, FIRSTNAME, LASTNAME, PRICE)>
<!ELEMENT TITLE (#PCDATA)>
<!ELEMENT FIRSTNAME (#PCDATA)>
<!ELEMENT LASTNAME (#PCDATA)>
<!ELEMENT PRICE (#PCDATA)>
<!ATTLIST BOOK ISBN ID #REQUIRED
BOOKCATEGORY (HISTORY | SCIENCE | FICTION) "FICTION">

14 eXtensible Markup Language ©NIIT


2_JAM_1.xml
<?xml version="1.0"?>
<!DOCTYPE BOOKDETAILS SYSTEM "2_JAM_1.dtd">
<BOOKDETAILS>
<BOOK ISBN="B001" BOOKCATEGORY="FICTION">
<TITLE>Monring, Noon, and Midnight</TITLE>
<FIRSTNAME>Sydney</FIRSTNAME>
<LASTNAME>Sheldon</LASTNAME>
<PRICE>10.00</PRICE>
</BOOK>
</BOOKDETAILS>

Solutions: Guided Practice


2.P.1
2_P_1.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="BOOKDETAILS" type="bdata"/>
<xsd:complexType name="bdata">
<xsd:sequence>
<xsd:element name="BOOK" type="bk"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="bk">
<xsd:sequence>
<xsd:element name="TITLE" type="xsd:string"/>
<xsd:element name="ISBN" type="isbnum"/>
<xsd:element name="FIRSTNAME" type="xsd:string"/>
<xsd:element name="LASTNAME" type="xsd:string"/>
<xsd:element name="PRICE" type="xsd:positiveInteger"/>
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="isbnum">
<xsd:restriction base="xsd:string">
<xsd:pattern value="[I]{1}\d{1}\d{1}\d{1}"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>

2_P_1.xml
<?xml version="1.0"?>
<BOOKDETAILS>
<BOOK>
<TITLE>An Equal Music</TITLE>
<ISBN>I001</ISBN>
<FIRSTNAME>Vikram</FIRSTNAME>
<LASTNAME>Seth</LASTNAME>
<PRICE>450</PRICE>
</BOOK>
</BOOKDETAILS>

©NIIT eXtensible Markup Language 15


Solutions: Unguided Practice

UGP 1.
2_UGP_1.xml
<?xml version="1.0"?>
<CUSTOMERDETAILS>
<CUSTOMER>
<CUSTOMERID>C098</CUSTOMERID>
<FIRSTNAME>Peter</FIRSTNAME>
<LASTNAME>Cole</LASTNAME>
<ADDRESS>24,Park Lane</ADDRESS>
</CUSTOMER>
</CUSTOMERDETAILS>

UGP 2.
2_UGP_2.dtd
<!ELEMENT STUDENTDETAILS (STUDENT)>
<!ELEMENT STUDENT (FNAME, LNAME, DATEOFBIRTH, SEM1MARK, SEM2MARK)>
<!ELEMENT FNAME (#PCDATA)>
<!ELEMENT LNAME (#PCDATA)>
<!ELEMENT DATEOFBIRTH (#PCDATA)>
<!ELEMENT SEM1MARK (#PCDATA)>
<!ELEMENT SEM2MARK (#PCDATA)>

2_UGP_2.xml
<?xml version="1.0"?>
<!DOCTYPE STUDENTDETAILS SYSTEM "2_UGP_2.dtd">
<STUDENTDETAILS>
<STUDENT>
<FNAME>Alice </FNAME>
<LNAME>Peterson</LNAME>
<DATEOFBIRTH>12/07/1974</DATEOFBIRTH>
<SEM1MARK>89</SEM1MARK>
<SEM2MARK>96</SEM2MARK>
</STUDENT>
</STUDENTDETAILS>

UGP 3.
2_UGP_3.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="MOVIEDETAILS" type="mdet"/>
<xsd:complexType name="mdet">
<xsd:sequence>
<xsd:element name="MOVIE" type="mve"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="mve">
<xsd:sequence>
<xsd:element name="TITLE" type="xsd:string"/>
<xsd:element name="MOVIEID" type="mid"/>
<xsd:element name="DIRNAME" type="xsd:string"/>
<xsd:element name="CAST" type="xsd:string"/>

16 eXtensible Markup Language ©NIIT


<xsd:element name="YEAROFRELEASE" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="mid">
<xsd:restriction base="xsd:string">
<xsd:pattern value="[M]{1}\d{1}\d{1}\d{1}"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>

2_UGP_3.xml
<?xml version="1.0"?>
<MOVIEDETAILS>
<MOVIE>
<TITLE>The Sixth Sense</TITLE>
<MOVIEID>M876</MOVIEID>
<DIRNAME>M Night Shyamalan</DIRNAME>
<CAST>Bruce Willis, Haley Joel Osment</CAST>
<YEAROFRELEASE>1999</YEAROFRELEASE>
</MOVIE>
</MOVIEDETAILS>

UGP 4.

2_UGP_4.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="RESERVATION" type="res"/>
<xsd:complexType name="res">
<xsd:sequence>
<xsd:element name="FROM" type="fromdef"/>
<xsd:element name="TO" type="fromdef"/>
<xsd:element name="FARE" type="xsd:positiveInteger"/>
<xsd:element name="DATE" type="xsd:date"/>
<xsd:element name="CLASS" type="classdef"/>
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="fromdef">
<xsd:restriction base="xsd:string">
<xsd:pattern value="(NY{1}|Chicago{1}|Miami{1}|Pittsburgh)"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="classdef">
<xsd:restriction base="xsd:string">
<xsd:pattern value="(First{1}|Executive{1}|Economy{1})"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>

2_UGP_4.xml
<?xml version="1.0"?>
<RESERVATION>
<FROM>NY</FROM>
<TO>Chicago</TO>
<FARE>200</FARE>
<DATE>2001-03-29</DATE>
<CLASS>Executive</CLASS>
</RESERVATION>

©NIIT eXtensible Markup Language 17


UGP 5.
2_UGP_5.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="ACCOUNTINFORMATION">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="MAILINFORMATION"
type="mailinfo"/>
<xsd:element name="ADDRESSBOOKINFORMATION"
type="addressbookinfo"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="mailinfo">
<xsd:sequence>
<xsd:element name="MAILTYPE" type="mailtype"/>
<xsd:element name="FROM" type="xsd:string"/>
<xsd:element name="SUBJECT" type="xsd:string"/>
<xsd:element name="DATE" type="xsd:date"/>
<xsd:element name="SIZE"
type="xsd:positiveInteger"/>
<xsd:element name="PRIORITY" type="priority"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="addressbookinfo">
<xsd:sequence>
<xsd:element name="QUICKNAME" type="xsd:string"/>
<xsd:element name="NAME" type="xsd:string"/>
<xsd:element name="EMAILID" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="mailtype">
<xsd:restriction base="xsd:string">
<xsd:pattern value="MAIL|NEWS"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="priority">
<xsd:restriction base="xsd:string">
<xsd:pattern value="LOW|MEDIUM|HIGH"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>

2_UGP_5.xml
<?xml version="1.0"?>
<ACCOUNTINFORMATION>
<MAILINFORMATION>
<MAILTYPE>NEWS</MAILTYPE>
<FROM>abcd@xyz.com</FROM>
<SUBJECT>Trial Mail</SUBJECT>
<DATE>2001-03-29</DATE>
<SIZE>12</SIZE>
<PRIORITY>LOW</PRIORITY>
</MAILINFORMATION>
<ADDRESSBOOKINFORMATION>
<QUICKNAME>trial</QUICKNAME>
<NAME>trial name</NAME>
<EMAILID>abcd@xyz.com</EMAILID>
</ADDRESSBOOKINFORMATION>
</ACCOUNTINFORMATION>

18 eXtensible Markup Language ©NIIT


Lesson Three
Experiences
You can begin the session by first explaining to the students that schemas use the same syntax as XML
documents. Unlike schemas, DTDs follow their own syntax.

Students must have a very clear and thorough understanding of what namespaces are and why they are
used in XML, because namespaces are used extensively in XML. You must explain the difference
between Web URIs and namespace URIs. Web URIs are used to locate a resource on the Web. They can
be used to find the physical location of a resource. On the other hand, namespace URIs just serve the
purpose of avoiding conflicting names of elements from two or more DTDs or schemas.

Examples and Analogies


Namespace is an abstract concept. Therefore, while explaining the concept of namespaces, talk about a
scenario where different programmers might create programs that contain elements that have the same
name but store different information. Then, you can discuss about the problems that will arise because
of the conflicting element names and how namespaces can be used to solve them. Explain that if there
are conflicting element names, the parser will not understand the context in which the elements are to be
validated. Therefore, there is an ambiguity. You specify namespaces to eliminate this ambiguity. You
can also specify that the prefix used with namespaces is just like an alias. In SQL Server, you use a short
name as an alias for a table that has a lengthy name. A namespace prefix serves also serves the same
purpose of reducing the time and efforts that would be required to type the complete namespace URI.

You must stress the fact that namespaces do not have a physical existence. They are just logical
addresses that help you to uniquely identify a component of an XML document.

Problem-wise Inputs
The demos for this lesson are stored in Lesson 3\demo folder of the TIRM CD.

3.D.1
The XML file for this demo is called 3_D_1.xml and the XSD file is called 3_D_1.xsd.

3.D.2
The XML file for this demo is called 3_D_2.xml. The common data types are stored in 3_D_2_a.xsd.
The schema for the XML document is stored in 3_D_2_b.xsd. To demonstrate the validation process,
open Learning Environment\index.htm in the browser. Click the Schema Validator link. Type the
name of the XML document as 3_D_2.xml (along with the path) and the name of the XSD file as
3_D_2_b.xsd. If the Schema Validator gives an error stating “Object Required”, please check whether
you have specified the correct path for the XML and XSD files.

FAQ
1. Should a user-defined data type be defined immediately after the declaration statement of the
attribute or element that it is associated with?

No. User-defined data types can be defined anywhere in the XSD document. The name attribute of
the data type is used to identify the data type. Therefore, it is not necessary for a user-defined data
type to be defined immediately after an attribute or element declaration statement.

©NIIT eXtensible Markup Language 19


2. Are there any rules regarding the names that can be use as namespace prefixes?

No. You can use any combination of letters as namespace prefixes. However, a short and
meaningful namespace prefix can save time and effort on the part of the programmer.

3. Is there a restriction on the number of times that an attribute can be referenced in an XSD
document?

No, an attribute can be referenced any number of times in an XSD document.

4. Can the value attribute of the attribute element be used to specify a list of valid values for the
user-defined attribute when the use attribute is set to required?

No. The value attribute can appear in the attribute declaration statement only when the use
attribute is set either to default or fixed.

5. Is there any equivalent of the ID value type of DTD in XML Schemas?

OR

How can I ensure that the value of an attribute is unique for every occurrence?

The key element of XSD can be used to ensure uniqueness of values contained in an element or an
attribute. However, this element does not work with MSXML 4.0 Beta 2.

Solutions: Just a Minute…


1. In addition to storing the name of the book, first and last names of the author, and price of the book,
you also need to store the book ID and the type of cover for each book. The type of cover can be
either hard or soft. Declare the elements and attributes required to store book details. The book ID
can also be used in different XML documents that store products data. Ensure that the book ID
attribute is reusable.
3_JAM_1.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:attribute name="BOOKID" type="xsd:string"/>
<xsd:element name="BOOKDATA" type="bodata"/>
<xsd:complexType name="bodata">
<xsd:sequence>
<xsd:element name="BOOK" type="bk"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="bk">
<xsd:sequence>
<xsd:element name="BOOKNAME" type="xsd:string"/>
<xsd:element name="AFNAME" type="xsd:string"/>
<xsd:element name="ALNAME" type="xsd:string"/>
<xsd:element name="PRICE" type="xsd:positiveInteger"/>
</xsd:sequence>
<xsd:attribute ref="BOOKID"/>
<xsd:attribute name="BOOKCOVER" type="bc" use="required"/>
</xsd:complexType>
<xsd:simpleType name="bc">
<xsd:restriction base="xsd:string">
<xsd:pattern value="Hard|Soft"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>

20 eXtensible Markup Language ©NIIT


3_JAM_1.xml
<?xml version="1.0"?>
<BOOKDATA>
<BOOK BOOKID="B001" BOOKCOVER="Soft">
<BOOKNAME>Jurassic Park</BOOKNAME>
<AFNAME>Michael</AFNAME>
<ALNAME>Crichton</ALNAME>
<PRICE>200</PRICE>
</BOOK>
</BOOKDATA>

2. The branch offices of CyberShoppe send the details about the sales made by them to the head
office. To ensure that the data can be accessed regardless of the hardware and software used at the
head office, the branches need to store their data in an XML format. When the head office receives
this data, it needs to verify that all branches have specified all required information. It also needs to
verify that the data sent by various branches is in a consistent format.

The sales details sent by various branch offices include the product ID, transaction ID, date of
transaction, customer ID, quantity ordered, and price per unit.

The product ID, the transaction ID, and the customer ID are used repeatedly in a number of
documents. Create reusable data types for storing these details. Also create an XML schema that
uses these data types for storing sales details. The product ID should contain the pattern “P[0-9][0-
9][0-9]”.

3_JAM_2_a.xsd
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="www.ecomatcybershop.com/sale">
<simpleType name="prstring">
<restriction base="string">
<pattern value="[P]{1}\d{3}"/>
</restriction>
</simpleType>
<simpleType name="orstring">
<restriction base="string">
<pattern value="[O]{1}\d{3}"/>
</restriction>
</simpleType>
<simpleType name="custstring">
<restriction base="string">
<pattern value="[C]{1}\d{3}"/>
</restriction>
</simpleType>
</schema>

3_JAM_2_b.xsd
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="www.ecomatcybershop.com/sale"
xmlns:prd="www.ecomatcybershop.com/sale">
<include schemaLocation="3_JAM_2_a.xsd"/>
<element name="SALES" type="prd:saletran"/>
<complexType name="saletran">
<sequence>
<element name="TRAN" type="prd:tran"/>
</sequence>
</complexType>
<complexType name="tran">
<sequence>

©NIIT eXtensible Markup Language 21


<element name="DATE" type="date"/>
<element name="QUANTITY" type="positiveInteger"/>
<element name="PRICEPERUNIT" type="positiveInteger"/>
</sequence>
<attribute name="PRODID" type="prd:prstring"/>
<attribute name="TRANID" type="prd:orstring" use="required"/>
<attribute name="CUSTID" type="prd:custstring" use="required"/>
</complexType>
</schema>

3_JAM_2.xml
<?xml version="1.0"?>
<prod:SALES xmlns:prod="www.ecomatcybershop.com/sale" >
<TRAN PRODID="P001" TRANID="O001" CUSTID="C001">
<DATE>2000-02-13</DATE>
<QUANTITY>3</QUANTITY>
<PRICEPERUNIT>20</PRICEPERUNIT>
</TRAN>
</prod:SALES>

While validating the above XML document, validate it against 3_JAM_2_b.xml.

Lesson Four
Problem-wise Inputs
At the end of this lesson, students will work on a comprehensive exercise, which covers all the concepts
learned about XML schemas.

Solutions: Just a Minute…


1. CyberShoppe sells books to its customers. The book details consist of the name of the book, the
name of the author of the book, and the price of the book. The name of the authors of the book can
be entered either by using the NAME element or by using the FIRSTNAME and LASTNAME
elements.
4_JAM_1.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:group name="auname">
<xsd:sequence>
<xsd:element name="FIRSTNAME" type="xsd:string"/>
<xsd:element name="LASTNAME" type="xsd:string"/>
</xsd:sequence>
</xsd:group>
<xsd:element name="BOOKS" type="bktype"/>
<xsd:complexType name="bktype">
<xsd:sequence>
<xsd:element name="BOOK" type="bk" minOccurs="1"
maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="bk">
<xsd:sequence>
<xsd:element name="TITLE" type="xsd:string"/>
<xsd:element name="AUTHOR" type="autype"/>
<xsd:element name="PRICE" type="xsd:positiveInteger" />
</xsd:sequence>

22 eXtensible Markup Language ©NIIT


</xsd:complexType>
<xsd:complexType name="autype">
<xsd:choice>
<xsd:group ref="auname"/>
<xsd:element name="NAME" type="xsd:string"/>
</xsd:choice>
</xsd:complexType>
</xsd:schema>

4_JAM_1.xml
<?xml version="1.0"?>
<BOOKS>
<BOOK>
<TITLE> If Tomorrow Comes </TITLE>
<AUTHOR>
<FIRSTNAME> Sydney </FIRSTNAME>
<LASTNAME> Sheldon </LASTNAME>
</AUTHOR>
<PRICE> 20 </PRICE>
</BOOK>
<BOOK>
<TITLE> The Client </TITLE>
<AUTHOR>
<NAME> John Grisham </NAME>
</AUTHOR>
<PRICE> 20 </PRICE>
</BOOK>
</BOOKS>

Solution: Guided Practice


4.P.1.

4_P_1_a.xsd
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.ecomatcybershoppe.com/supplier"
xmlns:supp="http://www.ecomatcybershoppe.com/supplier">
<simpleType name="suppstring">
<restriction base="string">
<pattern value="[S]{1}\d{3}"/>
</restriction>
</simpleType>
<complexType name="address">
<sequence>
<element name="STREET" type="string"/>
<element name="CITY" type="string"/>
<element name="STATE" type="string"/>
<element name="ZIP" type="string"/>
</sequence>
</complexType>
</schema>

4_P_1_b.xsd
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.ecomatcybershoppe.com/supplier"
xmlns:supp="http://www.ecomatcybershoppe.com/supplier">
<include schemaLocation="4_P_1_a.xsd"/>
<element name="SUPPLIERDETAILS">

©NIIT eXtensible Markup Language 23


<complexType>
<sequence>
<element name="SUPPLIER"
type="supp:suppdata" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>

<complexType name="suppdata">
<sequence>
<group ref="supp:suppgrp"/>
<element name="ADDRESS" type="supp:address"/>
<element name="PHONE" type="string"/>
<element name="TYPE" type="supp:suppliertype"/>
</sequence>
<attribute name="SUPPLIERID" type="supp:suppstring"/>
</complexType>

<group name="suppgrp">
<choice>
<sequence>
<element name="FIRSTNAME" type="string"/>
<element name="LASTNAME" type="string"/>
</sequence>
<element name="NAME" type="string" />
</choice>
</group>

<simpleType name="suppliertype">
<restriction base="string">
<pattern value="(Individual|Company)"/>
</restriction>
</simpleType>
</schema>

4_P_1.xml
<?xml version="1.0"?>
<supp1:SUPPLIERDETAILS
xmlns:supp1="http://www.ecomatcybershoppe.com/supplier">
<SUPPLIER SUPPLIERID="S001">
<FIRSTNAME> Keith </FIRSTNAME>
<LASTNAME> Williams </LASTNAME>
<ADDRESS>
<STREET> LIONS STREET </STREET>
<CITY> DAVENPORT</CITY>
<STATE> IOWA </STATE>
<ZIP> 234-1223 </ZIP>
</ADDRESS>
<PHONE> 294-234-1223 </PHONE>
<TYPE>Company</TYPE>
</SUPPLIER>
</supp1:SUPPLIERDETAILS>

Validate 4_P_1.xml against the schema contained in 4_P_1_b.xsd by using XML Schema Validator.

24 eXtensible Markup Language ©NIIT


Solution: Unguided Practice
UGP 1.

4_UGP_1.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="MOVIEDETAILS" type="mdata"/>
<xsd:complexType name="mdata">
<xsd:sequence>
<xsd:element name="MOVIE" type="mov"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="mov">
<xsd:sequence>
<xsd:element name="DATEOFRELEASE" type="xsd:date"/>
<xsd:element name="MOVIENAME" type="xsd:string"/>
<xsd:element name="CAST" type="xsd:string"/>
<xsd:element name="DIRECTOR" type="xsd:string"/>
<xsd:element name="AWARDS" type="xsd:string"/>
</xsd:sequence>
<xsd:attribute name="MOVIEID" type="xsd:string" use="required"/>
<xsd:attribute name="CATEGORY" type="cat" use="required"/>
<xsd:attribute name="LENGTH" type="xsd:positiveInteger"
use="required"/>
</xsd:complexType>
<xsd:simpleType name="cat">
<xsd:restriction base="xsd:string">
<xsd:pattern value="Horror|Comedy|Romance|Drama|Action"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>

4_UGP_1.xml
<?xml version="1.0"?>
<MOVIEDETAILS>
<MOVIE MOVIEID="M007" CATEGORY="Horror" LENGTH="120">
<DATEOFRELEASE>1973-04-18</DATEOFRELEASE>
<MOVIENAME>The Exorcist</MOVIENAME>
<CAST>Ellen Burstyn</CAST>
<DIRECTOR>William Friedkin</DIRECTOR>
<AWARDS>3</AWARDS>
</MOVIE>
</MOVIEDETAILS>

UGP 2.
4_UGP_2_a.xsd
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.ecomatcybershoppe.com/employee"
xmlns:emp="http://www.ecomatcybershoppe.com/employee">
<simpleType name="empstring">
<restriction base="string">
<pattern value="[E]{1}\d{3}"/>
</restriction>
</simpleType>
</schema>

©NIIT eXtensible Markup Language 25


4_UGP_2_b.xsd
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.ecomatcybershoppe.com/employee"
xmlns:emp="http://www.ecomatcybershoppe.com/employee">

<include schemaLocation="4_UGP_2_a.xsd"/>

<element name="EMPLOYEEDETAILS">
<complexType>
<sequence>
<element name="EMPLOYEE"
type="emp:empdata" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>

<complexType name="empdata">
<sequence>
<element name="NAME" type="string"/>
<element name="ADDRESS" type="string"/>
<element name="DESIGNATION" type="string"/>
<element name="DEPARTMENT" type="string"/>
<element name="DATEOFJOINING" type="date"/>
</sequence>
<attribute name="EMPID" type="emp:empstring"/>
</complexType>
</schema>

4_UGP_2.xml
<?xml version="1.0"?>
<emp1:EMPLOYEEDETAILS
xmlns:emp1="http://www.ecomatcybershoppe.com/employee">
<EMPLOYEE EMPID="E001">
<NAME>John</NAME>
<ADDRESS>12,</ADDRESS>
<DESIGNATION>Sales Executive</DESIGNATION>
<DEPARTMENT>Sales and Invoicing </DEPARTMENT>
<DATEOFJOINING>2001-03-29</DATEOFJOINING>
</EMPLOYEE>
</emp1:EMPLOYEEDETAILS>

UGP 3.
4_UGP_3.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<xsd:element name="JOBDETAILS">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="JOB" type="jobinformation"
maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="jobinformation">
<xsd:sequence>
<xsd:element name="COMPANYNAME"
type="xsd:string"/>

26 eXtensible Markup Language ©NIIT


<xsd:element name="JOBDESCRIPTION"
type="xsd:string"/>
<xsd:element name="EXPERIENCE"
type="xsd:nonNegativeInteger"/>
<xsd:element name="QUALIFICATION"
type="qualificationtype"/>

<xsd:element name="CONTACTINFO"
type="contactinfo"/>

<xsd:element name="SALARY" type="xsd:positiveInteger"/>


<xsd:element name="JOBTYPE" type="jobtype"/>
</xsd:sequence>
<xsd:attribute name="JOBID" type="jobid"
use="required"/>
</xsd:complexType>

<xsd:complexType name="qualificationtype">
<xsd:choice>
<xsd:element name="STRICTQUALIFICATION"
type="strictqual" />
<xsd:element name="RELAXEDQUALIFICATION"
type="relaxedqual" />
</xsd:choice>
</xsd:complexType>

<xsd:complexType name="strictqual">
<xsd:group ref="strictqualref" />
</xsd:complexType>

<xsd:complexType name="relaxedqual">
<xsd:choice>
<xsd:element name="GRADUATE" type="xsd:string"/>
<xsd:element name="POSTGRADUATE"
type="xsd:string"/>
</xsd:choice>
</xsd:complexType>

<xsd:group name="strictqualref">
<xsd:sequence>
<xsd:element name="GRADUATE" type="xsd:string"/>
<xsd:element name="POSTGRADUATE"
type="xsd:string"/>
</xsd:sequence>
</xsd:group>

<xsd:simpleType name="jobid">
<xsd:restriction base="xsd:string">
<xsd:pattern value="[J]\d{3}"/>
</xsd:restriction>

</xsd:simpleType>
<xsd:complexType name="contactinfo">
<xsd:choice>
<xsd:element name="EMAIL" type="xsd:string" />
<xsd:element name="ADDRESS" type="xsd:string" />
</xsd:choice>
</xsd:complexType>

©NIIT eXtensible Markup Language 27


<xsd:simpleType name="jobtype">
<xsd:restriction base="xsd:string">
<xsd:pattern value= "(CONTRACT|PERMANENT)"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>

4_UGP_3.xml
<?xml version="1.0"?>
<JOBDETAILS>
<JOB JOBID="J001">
<COMPANYNAME>Flamingo Inc. </COMPANYNAME>
<JOBDESCRIPTION>MKTG MGR</JOBDESCRIPTION>
<EXPERIENCE>3</EXPERIENCE>
<QUALIFICATION>
<STRICTQUALIFICATION>
<GRADUATE>Bachelor of Commerce</GRADUATE>
<POSTGRADUATE>Business Admin</POSTGRADUATE>
</STRICTQUALIFICATION>
</QUALIFICATION>
<CONTACTINFO>
<EMAIL>abc@xyz.com</EMAIL>
</CONTACTINFO>
<SALARY>5000</SALARY>
<JOBTYPE>PERMANENT</JOBTYPE>
</JOB>
<JOB JOBID="J002">
<COMPANYNAME>ABC Inc.</COMPANYNAME>
<JOBDESCRIPTION>Tech Writing</JOBDESCRIPTION>
<EXPERIENCE>3</EXPERIENCE>
<QUALIFICATION>
<RELAXEDQUALIFICATION>
<GRADUATE>B.A.</GRADUATE>
</RELAXEDQUALIFICATION>
</QUALIFICATION>
<CONTACTINFO>
<EMAIL>abc@xyz.com</EMAIL>
</CONTACTINFO>
<SALARY>1200</SALARY>
<JOBTYPE>CONTRACT</JOBTYPE>
</JOB>
</JOBDETAILS>

Lesson Five
Experiences
You can start this session by talking about rendering and how data can be presented on a variety of
targets, such as Web browsers, e-mail, pagers, and cell phones. Talk about the different rendering
languages that are used for rendering data to these devices. Besides CSS and XSL, you also have
rendering languages such as DSSSL. DSSSL has been covered in the Appendix. It is recommended that
you read the section on DSSSL before taking this class.

Explain the importance of formatting data before explaining the concept of style sheets. Re-emphasize
the fact that XML is a markup language for providing structure to the content and not for presenting
data to the user. Therefore, you require style sheets.

28 eXtensible Markup Language ©NIIT


Both the CSS and XSL files can be created using Notepad and saved with css and xsl extensions,
respectively.

By using CSS to render data in a browser, the actual data is separated from the information required to
present the data. This ensures that the same XML document can be rendered across for purposes, such
as printing, displaying data on the Web and making presentations. This does not result in the
modification of data as the two are separated.

Explain the syntax for coding a CSS file. In order to associate the formatting information to the XML
document, students need to use the following syntax in the XML file:

<?xml:stylesheet type="text/css" href="path-name"?>

To view the output, students need to open the XML file using the browser.

While talking about XSL, tell students that CSS cannot be used for performing operations, such as
reordering and sorting elements based on a condition.

While explaining the working of the XSLT processor, mention that the version of MSXML parser that
comes along with IE 5.0 is 2.5. The beta version of MS XML 4.0 parser is currently available at the
following site:

http://www.microsoft.com/downloads

It is also important to state that the MSXML parser that comes along with IE 5.0 is an older version.
Therefore, it does not support many of the tags of XSLT. Also, the namespace declarations for old XSL
specification is given as follows:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">

On the other hand, the newer specification uses the following namespace declaration:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version=“1.0”>

You are very likely to face a question from students regarding the XSLT and XPATH Learning Module
form. State that we are using this form because IE 5.0 uses MSXML 2.5. Even if you load MSXML 4.0,
the newer version runs side-by-side with the older version. Therefore, when you try associate the XSLT
document with the XML document, IE 5.0 does not recognize the namespace URI. It still recognizes the
old namespace URI. Therefore, you need to use this script. This script loads XML document and XSLT
style sheet into various objects and applies the XSLT style sheet to the XML document. Also inform the
students that they will learn to write such a script in Lesson 8.

Examples and Analogies


The purpose of formatting data and presenting it in different colors and fonts can be explained as a
method of gaining the attention of students. For example, while presenting information about ticket
details, the name of the wait-listed passengers can be presented in a color different from that of the
passengers whose tickets are confirmed.

While explaining sorting of data, you can state that the sort element of XSLT is similar to the ORDER
BY clause in SQL Server. Also state that you can have multiple sort elements within a for-each element.
Therefore, you can easily sort based on two or more elements.

©NIIT eXtensible Markup Language 29


FAQ
1. Can I use both CSS and XSLT together?

Yes. You can use XSLT to transform XML data into structures, such as lists or tables, and then
apply CSS to the result to control how these structures appear in the appropriate medium.

2. Where can I use the xsl:sort element?

The xsl:sort element can be used as a child for the xsl:for-each element or xsl:apply-templates
element.

3. Why is the xsl:apply-templates element used?

The xsl:apply-templates element is used in case of templates-based formatting. The xsl:apply-


templates element directs the XSLT processor to find an appropriate xsl:template to apply.

Solutions: Just a Minute…


1. The details about all the books sold at CyberShoppe are to be displayed in the following format:

„ The book name is to be displayed in blue color, Times New Roman font, size 20pts, and bold.

„ The first name and last name of the author are to be displayed in green color, Arial font, and
size 10pts.

„ Price of the book is to be displayed in red color, Times New Roman, and size 20pts.
Create a CSS for displaying the book details in the above format.
5_JAM_1.xml
<?xml version="1.0"?>
<?xml:stylesheet type="text/css" href="5_JAM_1.css"?>
<BOOKDETAILS>
<BOOK BOOKID="B001">
<BOOKNAME>ANNE OF GREEN GABLES</BOOKNAME>
<AFNAME>LUCY MAUD</AFNAME>
<ALNAME>MONTGOMERY</ALNAME>
<PRICE>150.00</PRICE>
</BOOK>
<BOOK BOOKID="B002">
<BOOKNAME>MIND READING IN PUBLIC</BOOKNAME>
<AFNAME>ABBOTT</AFNAME>
<ALNAME>DAVID PHELPS</ALNAME>
<PRICE>250.00</PRICE>
</BOOK>
<BOOK BOOKID="B003">
<BOOKNAME>THE OUTLET</BOOKNAME>
<AFNAME>ADAMS</AFNAME>
<ALNAME>ANDY</ALNAME>
<PRICE>200.00</PRICE>
</BOOK>
</BOOKDETAILS>

30 eXtensible Markup Language ©NIIT


5_JAM_1.css
BOOKNAME
{
font-family:Times New Roman;
font-size:20pts;
font-weight:bold;
color:blue;
}
AFNAME,ALNAME
{
font-family:Arial;
font-size:10pts;
color:green;
}
PRICE
{
font-family:Times New Roman;
font-size:20pts;
color:red;
}

Solutions: Guided Practice

5.P.1.

5_P_1.xml
<?xml version="1.0"?>
<BOOKDETAILS>
<BOOK BOOKID="B001">
<TITLE>ANNE OF GREEN GABLES</TITLE>
<AFNAME>LUCY MAUD</AFNAME>
<ALNAME>MONTGOMERY</ALNAME>
<PRICE>150.00</PRICE>
</BOOK>
<BOOK BOOKID="B002">
<TITLE>MIND READING IN PUBLIC</TITLE>
<AFNAME>ABBOTT</AFNAME>
<ALNAME>DAVID PHELPS</ALNAME>
<PRICE>250.00</PRICE>
</BOOK>
<BOOK BOOKID="B003">
<TITLE>THE OUTLET</TITLE>
<AFNAME>ADAMS</AFNAME>
<ALNAME>ANDY</ALNAME>
<PRICE>200.00</PRICE>
</BOOK>
</BOOKDETAILS>

5_P_1.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<xsl:for-each select="BOOKDETAILS/BOOK">
<xsl:sort select="PRICE" />

©NIIT eXtensible Markup Language 31


<xsl:sort select="@BOOKID" />
<LI>
<xsl:value-of select="@BOOKID"/>
<xsl:value-of select="TITLE"/>
<xsl:value-of select="PRICE"/>
</LI>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Lesson Six
Experiences
You can start this session by explaining the importance of XPath. It is a query language defined for
XML that provides a simple syntax to select the subset of nodes in a XML document. XPath treats an
XML document as a tree of interrelated branches and nodes, where a node can be any of the following
in the document: an element, attribute, processing instruction (PI), comment, text, or namespace.

Tell students that XPath expressions can be created using a set of operators and special characters. You
can ask students to write a few XPath expressions using these operators and special characters.

Talk about the values that an XPath function can return and then discuss about the different types of
functions, such as string, node-set, Boolean, and number. By using the operators and the XPath
functions, students can calculate data and present it in the form of a summary report.

Make sure that the Learning Environment folder is present on all student machines. If the XML and
XSLT files are in different folders, ask the students to type in the entire path of these files in the
appropriate text boxes of the XSLT and XPATH Learning Module form.

You can begin the section on using HTML tags within XSLT by first talking about the limitations of
XML with respect to the way in which data is displayed to the user. You can then explain the various
formatting options supported by HTML.

Examples and Analogies


While talking about how XPath treats an XML document as a tree of interrelated branches and nodes,
you can compare it with the tree-view of Windows Explorer. Each folder in Windows Explorer can be
compared to a node in the tree-view structure of an XML document.

You can compare the XPath functions with functions of any other programming language for better
understanding. The programming language that you discuss must be based on the batch profile.

While explaining the xsl:if and xsl:choose elements, compare them with the if-then construct and
switch-case construct respectively.

FAQ
1. When is the * operator used?

The * operator can be used for selecting all elements regardless of the element name. It can also be
used for multiplying two numbers.

32 eXtensible Markup Language ©NIIT


2. What does the following code indicate?

STUDENTDTLS/STUDENT[@ID='S001']

The given code is a sample XPath expression used for retrieving the STUDENT element, which is a
child of the root element, STUDENTDTLS and that has an ID attribute with the value S001.

3. What does boolean(-100) return?

Boolean(-100) will return true.

4. Why do I get the value “NaN” for some of the calculations that I attempt?

NaN stands for Not a Number. This value is usually displayed when calculations are performed on
text nodes or the path specified for nodes is not correct. Check your XPath expression if you get
this kind of an error.

Solutions: Just a Minute…


1. The details about books sold at CyberShoppe need to be displayed. Books priced higher than $100
are to be displayed in red color, those priced higher than $75 are to be displayed in blue, and the
rest are to be displayed in green color.

6_JAM_1.xml
<?xml version="1.0"?>
<BOOKDETAILS>
<BOOK BOOKID="B001">
<BOOKNAME>ANNE OF GREEN GABLES</BOOKNAME>
<AFNAME>LUCY MAUD</AFNAME>
<ALNAME>MONTGOMERY</ALNAME>
<PRICE>50.00</PRICE>
</BOOK>
<BOOK BOOKID="B002">
<BOOKNAME>MIND READING IN PUBLIC</BOOKNAME>
<AFNAME>ABBOTT</AFNAME>
<ALNAME>DAVID PHELPS</ALNAME>
<PRICE>250.00</PRICE>
</BOOK>
<BOOK BOOKID="B003">
<BOOKNAME>THE OUTLET</BOOKNAME>
<AFNAME>ADAMS</AFNAME>
<ALNAME>ANDY</ALNAME>
<PRICE>76.00</PRICE>
</BOOK>
</BOOKDETAILS>

6_JAM_1.xsl
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<xsl:for-each select="BOOKDETAILS/BOOK">
<xsl:choose>
<xsl:when test="PRICE[. &gt; 100]">
<font color="red">
BOOK NAME:<xsl:value-of select="BOOKNAME"/><BR/>
AUTHOR: <xsl:value-of select="AFNAME"/> <xsl:text>
</xsl:text> <xsl:value-of select="ALNAME" /><BR/>

©NIIT eXtensible Markup Language 33


PRICE: <xsl:value-of select="PRICE"/><BR/>
<HR/> <!--Displays a horizontal rule -->
</font>
</xsl:when>
<xsl:when test="PRICE[. &gt; 75 and . &lt; 100]">
<font color="blue">
BOOK NAME:<xsl:value-of select="BOOKNAME"/><BR/>
AUTHOR: <xsl:value-of select="AFNAME"/> <xsl:text>
</xsl:text> <xsl:value-of select="ALNAME" /><BR/>
PRICE: <xsl:value-of select="PRICE"/><BR/>
<HR/> <!--Displays a horizontal rule -->
</font>
</xsl:when>
<xsl:otherwise>
<font color="green">
BOOK NAME:<xsl:value-of select="BOOKNAME"/><BR/>
AUTHOR: <xsl:value-of select="AFNAME"/> <xsl:text>
</xsl:text> <xsl:value-of select="ALNAME" /><BR/>
PRICE: <xsl:value-of select="PRICE"/><BR/>
<HR/> <!--Displays a horizontal rule -->
</font>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Solutions: Guided Practice


6.P.1.
6_P_1.xml
<?xml version="1.0"?>
<SUPPLIERDATA>
<SUPPLIER SUPPID="S001">
<FIRSTNAME> JANE </FIRSTNAME>

<LASTNAME> PETERSON </LASTNAME>


<ADDRESS> 10, LIONS RD, BOSTON </ADDRESS>
<PHONE> 344-345-4456 </PHONE>
<PRODUCT PRODID="P001">
<PRODUCTNAME> BARBIE DOLL </PRODUCTNAME>
<DESCRIPTION> TOY FOR CHILDREN IN THE AGE
GROUP OF 5-10 </DESCRIPTION>
<PRICE> 20 </PRICE>
</PRODUCT>
<PRODUCT PRODID="P002">
<PRODUCTNAME> MINI BUS </PRODUCTNAME>
<DESCRIPTION> TOY FOR CHILDREN IN THE AGE
GROUP OF 6-11 </DESCRIPTION>
<PRICE> 75 </PRICE>
</PRODUCT>
</SUPPLIER>
<SUPPLIER SUPPID="S002">
<FIRSTNAME> Peter </FIRSTNAME>
<LASTNAME> Mathew </LASTNAME>
<ADDRESS> 15, LIONS RD, BOSTON </ADDRESS>

34 eXtensible Markup Language ©NIIT


<PHONE> 344-345-4346 </PHONE>
<PRODUCT PRODID="P003">
<PRODUCTNAME> TEDDY BEAR </PRODUCTNAME>
<DESCRIPTION> TOY FOR CHILDREN IN THE AGE
GROUP OF 5-10 </DESCRIPTION>
<PRICE> 10 </PRICE>
</PRODUCT>
</SUPPLIER>
<SUPPLIER SUPPID="S003">
<FIRSTNAME> John </FIRSTNAME>
<LASTNAME> Norton </LASTNAME>
<ADDRESS> 20, LIONS RD, BOSTON </ADDRESS>
<PHONE> 344-345-2346 </PHONE>
<PRODUCT PRODID="P001">
<PRODUCTNAME> BARBIE DOLL</PRODUCTNAME>
<DESCRIPTION> TOY FOR CHILDREN IN THE AGE
GROUP OF 5-10 </DESCRIPTION>
<PRICE> 20 </PRICE>
</PRODUCT>
</SUPPLIER>
<SUPPLIER SUPPID="S004">
<FIRSTNAME> Nick </FIRSTNAME>
<LASTNAME> Mathew </LASTNAME>
<ADDRESS> 25, LIONS RD, BOSTON </ADDRESS>
<PHONE> 344-345-3445 </PHONE>
<PRODUCT PRODID="P005">
<PRODUCTNAME> TRAIN </PRODUCTNAME>
<DESCRIPTION> TOY FOR CHILDREN IN THE AGE
GROUP OF 5-10 </DESCRIPTION>
<PRICE> 50 </PRICE>
</PRODUCT>
</SUPPLIER>

</SUPPLIERDATA>

6_P_1.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="PRODUCT">
<xsl:value-of select="PRODUCTNAME" />
<xsl:if test="position()!=last()"> , </xsl:if>
</xsl:template>
<xsl:template match="/">
<table border="2">
<thead>
<tr>
<th> ID </th> <th> First Name </th> <th> Last Name </th> <th>
Address </th>
<th> Phone </th> <th> Products </th>
</tr>
</thead>
<tbody>
<xsl:for-each select="SUPPLIERDATA/SUPPLIER">
<tr>
<xsl:choose>
<xsl:when test="position() mod 2 = 0">

<td> <font color="red"><xsl:value-of

©NIIT eXtensible Markup Language 35


select="@SUPPID"/> </font></td>
<td><font color="red"><xsl:value-of
select="FIRSTNAME"/></font></td>
<td><font color="red"><xsl:value-of
select="LASTNAME"/></font></td>
<td><font color="red"><xsl:value-of
select="ADDRESS"/></font></td>
<td> <font color="red"><xsl:value-of
select="PHONE"/> </font></td>
<td><font color="red"><xsl:apply-templates
select="PRODUCT"/> </font></td>
</xsl:when>
<xsl:otherwise>
<td> <xsl:value-of select="@SUPPID"/></td>
<td><xsl:value-of select="FIRSTNAME"/></td>
<td><xsl:value-of select="LASTNAME"/></td>
<td><xsl:value-of select="ADDRESS"/></td>
<td> <xsl:value-of select="PHONE"/> </td>
<td><xsl:apply-templates select="PRODUCT"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</tbody>
</table>
</xsl:template>
</xsl:stylesheet>

Solution to the Unguided Practice


UGP 1.

6_UGP_1.xml
<?xml version="1.0"?>
<?xml:stylesheet type="text/css" href="6_UGP_1.css"?>
<EMPDETAILS>
<EMP EMPID="E001">
<ENAME>Karen</ENAME>
<DESG>MANAGER</DESG>
<DEPT>SALES</DEPT>
<SALARY>250</SALARY>
</EMP>
<EMP EMPID="E002">
<ENAME>George</ENAME>
<DESG>Executive</DESG>
<DEPT>ACCOUNTS</DEPT>
<SALARY>300</SALARY>
</EMP>
<EMP EMPID="E003">
<ENAME>Steve</ENAME>
<DESG>Manager</DESG>
<DEPT>FINANCE</DEPT>
<SALARY>320</SALARY>
</EMP>
<EMP EMPID="E004">
<ENAME>Ricky</ENAME>
<DESG>Clerk</DESG>
<DEPT>SALES</DEPT>
<SALARY>150</SALARY>

36 eXtensible Markup Language ©NIIT


</EMP>
<EMP EMPID="E005">
<ENAME>Richard</ENAME>
<DESG>Divisional Manager</DESG>
<DEPT>MARKETING</DEPT>
<SALARY>375</SALARY>
</EMP>
</EMPDETAILS>

6_UGP_1.css
ENAME,SALARY
{
font-family:Times New Roman;
font-size:20pts;
color:blue;
}

DESG,DEPT
{
font-family:Arial;
font-size:10pts;
color:green;
}

UGP 2.
6_UGP_2.xml
<?xml version="1.0"?>
<?xml:stylesheet type="text/xsl" href="6_UGP_2.xsl"?>
<EMPDETAILS>
<EMP EMPID="E001">
<ENAME>Karen</ENAME>
<DESG>MANAGER</DESG>
<DEPT>SALES</DEPT>
<SALARY>230</SALARY>
</EMP>
<EMP EMPID="E002">
<ENAME>George</ENAME>
<DESG>Executive</DESG>
<DEPT>ACCOUNTS</DEPT>
<SALARY>300</SALARY>
</EMP>
<EMP EMPID="E003">
<ENAME>Steve</ENAME>
<DESG>Manager</DESG>
<DEPT>FINANCE</DEPT>
<SALARY>320</SALARY>
</EMP>
<EMP EMPID="E004">
<ENAME>Ricky</ENAME>
<DESG>Clerk</DESG>
<DEPT>SALES</DEPT>
<SALARY>150</SALARY>
</EMP>
<EMP EMPID="E005">
<ENAME>Richard</ENAME>
<DESG>Divisional Manager</DESG>
<DEPT>MARKETING</DEPT>
<SALARY>375</SALARY>
</EMP>
</EMPDETAILS>

©NIIT eXtensible Markup Language 37


6_UGP_2.xsl
<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<xsl:for-each select="EMPDETAILS/EMP">
<xsl:choose>
<xsl:when test="SALARY[. &gt; 250]">
<font color="green" />
<li>
<xsl:value-of select="ENAME" />
</li>
<br />
<li>
<xsl:value-of select="DESG" />
</li>
<br />
<li>
<xsl:value-of select="DEPT" />
</li>
<br />
<li>
<xsl:value-of select="SALARY" />
</li>
<br />
</xsl:when>
<xsl:otherwise>
<font color="blue" />
<li>
<xsl:value-of select="ENAME" />
</li>
<br />
<li>
<xsl:value-of select="DESG" />
</li>
<br />
<li>
<xsl:value-of select="DEPT" />
</li>
<br />
<li>
<xsl:value-of select="SALARY" />
</li>
<br />
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

UGP 3.

6_UGP_3.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="6_UGP_3.xsl"?>
<EMPDETAILS>
<EMP>
<EMPNAME>William Hill</EMPNAME>
<DOB>1965/3/19</DOB>

38 eXtensible Markup Language ©NIIT


<ADDRESS>13, Cross Street</ADDRESS>
<DESIG>Manager</DESIG>
</EMP>
<EMP>
<EMPNAME>Peter Hall</EMPNAME>
<DOB>1945/8/1</DOB>
<ADDRESS>24, Orange Street</ADDRESS>
<DESIG>Secretary</DESIG>
</EMP>
<EMP>
<EMPNAME>David Alexander</EMPNAME>
<DOB>1980/12/24</DOB>
<ADDRESS>10, Anchor Street</ADDRESS>
<DESIG>Manager</DESIG>
</EMP>
</EMPDETAILS>

6_UGP_3.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<html>
<body>
<table border="2" bgcolor="yellow">
<tr>
<th>Employee Name</th>
<th>Date of Birth</th>
<th>Address</th>
<th>Designation</th>
</tr>
<xsl:for-each select="EMPDETAILS/EMP">
<tr>
<td><xsl:value-of select="EMPNAME"/></td>
<td><xsl:value-of select="DOB"/></td>
<td><xsl:value-of select="ADDRESS"/></td>
<td><xsl:value-of select="DESIG"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html></xsl:template></xsl:stylesheet>

UGP 4.
6_UGP_4.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="6_UGP_4.xsl"?>
<CUSTDETAILS>
<CUSTOMER CUSTID="C001">
<CUSTNAME>William Anderson</CUSTNAME>
<ADDRESS>13, Cross Street</ADDRESS>
<CITY>New York</CITY>
<STATE>New York</STATE>
<COUNTRY>USA</COUNTRY>
<PHONE>6785764</PHONE>
</CUSTOMER>
<CUSTOMER CUSTID="C002">
<CUSTNAME>Bill Sanders</CUSTNAME>
<ADDRESS>13, Crick Street</ADDRESS>
<CITY>Seattle</CITY>
<STATE>Washington</STATE>

©NIIT eXtensible Markup Language 39


<COUNTRY>USA</COUNTRY>
<PHONE>608475</PHONE>
</CUSTOMER>
</CUSTDETAILS>

6_UGP_4.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<html>
<body>
<xsl:for-each select="CUSTDETAILS/CUSTOMER">
<li><xsl:value-of select="@CUSTID"/></li>
<li><xsl:value-of select="CUSTNAME"/></li>
<li><xsl:value-of select="ADDRESS"/></li>
<li><xsl:value-of select="CITY"/></li>
<li><xsl:value-of select="STATE"/></li>
<li><xsl:value-of select="COUNTRY"/></li>
<li><xsl:value-of select="PHONE"/></li>
<br></br>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Lesson Seven
Experiences
Introduce the functions of a parser in terms of its disadvantages, as the parser alone will not allow you to
traverse from one portion of the XML document to the other. Then, introduce the Document Object
Model (DOM) as a solution for the same. Refer to the latest at www.W3C.org on development of DOM
for XML.

Instruct the students that the “I” in the IXMLDOMNode, IXMLDOMNodeList, and
IXMLDOMParseError objects stands for interface. These are the basic interfaces, which are
implemented by various objects of XML DOM.

Solutions: Just a Minute…


1. The details about products sold at CyberShoppe are stored in an XML document called
product.xml. Write the code to display the price of all products by using DOM objects.
7_JAM_1.htm
<html>
<head>
<script language="JavaScript">

function loadXML()
{
var myxmlDoc = new ActiveXObject("Msxml2.DOMDocument.4.0")
myxmlDoc.async=false
myxmlDoc.load("products.xml")
var myelement = myxmlDoc.getElementsByTagName("PRICE");
for (i=0; i<= myelement.length -1; ++i)
{

40 eXtensible Markup Language ©NIIT


alert(myelement.item(i).text)
}
}
</script>
</head>
<body onLoad="loadXML()">
</body>
</html>

products.xml
<?xml version="1.0"?>
<PRODUCTDATA>
<PRODUCT>
<PRODUCTNAME>Barbie Doll</PRODUCTNAME>
<DESCRIPTION>This is a doll for children aged 11 and
above</DESCRIPTION>
<PRICE>10</PRICE>
<QUANTITY>12</QUANTITY>
</PRODUCT>
<PRODUCT>
<PRODUCTNAME>Mini Bus</PRODUCTNAME>
<DESCRIPTION>This is a toy for children aged 11 and
above</DESCRIPTION>
<PRICE>20</PRICE>
<QUANTITY>12</QUANTITY>
</PRODUCT>
</PRODUCTDATA>

To execute the script, open the 7_JAM_1.htm page in the browser. As soon as the page is loaded in the
browser, it will display message boxes displaying the prices of products. Notice that the
getElementsByTagName function is used here to retrieve values of all elements named PRICE. Then,
you can display these values by using the for loop to traverse through the node list returned by the
getElementsByTagName() function.

Lesson Eight
Experiences
You can begin the session by giving a brief recap about the various DOM objects discussed in the
previous lesson. Ensure that the student understands the main methods and properties that are associated
with each of the four objects.

You can then explain the scenario that is specified for this lesson. This can be followed by an
explanation of the objects that are required to process an XML documents using a style sheet document.

First, create the XML and XSD documents. Next, you can talk about the code that is required to process
the XML and XSD documents. You can also create the HTML documents that are required to display
information to the end user. Finally, explain the JavaScript code that must be used to link the various
HTML and XML documents.

©NIIT eXtensible Markup Language 41


Examples and Analogies
You can compare the working of DOM with that of a linked list. First, explain the different parts of a
linked list and the mechanism used to traverse a linked list. You can then compare this process with the
way in which the DOM node tree is traversed.

Additional Inputs
One of the methods of applying an XSLT style sheet to an XML document is by using the
XSLProcessor and XSLTemplate objects. These objects provide the advantages of working on a cached
version of style sheets and support for asynchronous mode of loading XML document. Another simple
way of applying an XSLT style sheet to the XML document is by using the transformNode() method of
the DOMDocument object, as shown in the following example:

<HTML>

<HEAD>

<SCRIPT LANGUAGE="JavaScript">

function LOADXML()

var xmldoc=new ActiveXObject("Msxml2.DOMDocument.4.0");

xmldoc.async=false;

xmldoc.load("product.xml");

var xsldoc=new ActiveXObject("Msxml2.DOMDocument.4.0");

xsldoc.async=false;

xsldoc.load("productlist.xsl");

x.innerHTML = xmldoc.transformNode(xsldoc);

</SCRIPT>

</HEAD>

<BODY onload="LOADXML()">

<div id="x">

</div>

</BODY>

</HTML>

The above code creates two instances of the DOMDocument object, one for loading the XML document
and the other for loading the XSLT style sheet. Then, it calls the transformNode() method of the

42 eXtensible Markup Language ©NIIT


DOMDocument object that contains the XML document and passes as an argument a reference of the
other DOMDocument that contains the XSLT style sheet. The transformNode() method transforms the
XML document into the specified format by applying the style sheet, which is displayed in the browser
window. This is another simpler method of dynamically applying an XSLT style sheet to an XML
document. However, the transformNode() method is a Microsoft extension to the W3C DOM.

FAQ
1. What does Msxml2.FreeThreadedDOMDocument stand for?

Msxml2.FreeThreadedDOMDocument is used to create a free threaded object. There are two kinds
of threading models, rental and free-threaded. The rental model enables for single threaded access
in which all objects are executed on a single thread. The free-threaded model enables multi-
threaded access. In this model, an object can be executed on any thread at any time.

2. What is cache memory?

Cache is a section of the memory of the computer that is made up of high speed Static Random
Access Memory (SRAM) Information stored in the cache can be accessed faster than other portions
of the RAM.

3. Is there a method by which I transform a single node?

Yes , there is. You can use the transformNode() method of the XMLDOMNode object to transform
the information contained in a node and all its child nodes.

Solutions: Just a Minute…


1. Write the code to add an XML schema called “products.xsd” to a schema collection.

Solution:
var xsdschemacache = new ActiveXObject("Msxml2.XMLSchemaCache.4.0");
var xmlDoc = new
ActiveXObject("Msxml2.FreeThreadedDOMDocument.4.0");
xmlDoc.validateOnParse=true
xmlDoc.load("products.xml");
var namespace=xmlDoc.namespaceURI;
xsdschemacache.add(namespace,"products.xsd");
2. The following JavaScript code is used create XSLTemplate and DOMDocument objects. Identify
the errors in the code, if any.

custss = new activexObject(MSXML.XSLTemplate.4)


custdomdoc = activexobject( "MSXML.ThreadedDOMdocument.4.0);

Solution:
custss= new ActiveXObject("MSXML2.XSLTemplate.4.0");
custdomdoc = new
ActiveXObject("MSXML2.FreeThreadedDOMDocument.4.0");

©NIIT eXtensible Markup Language 43


3. Identify the errors in the following JavaScript code:
xslProcObject.output=xmlDocObject;
xslProcObject.Transform
alert("xslProcObject");

Solution:
xslProcObject.input=xmlDocObject;
xslProcObject.transform();
alert(xslProcObject.output);

Solutions: Guided Practice


8.P.1

The XML document containing the book details is given below:


8_P_1.xml
<?xml version="1.0"?>
<BOOKDETAILS>
<BOOK BOOKID="B001">
<TITLE> MORNING, NOON, AND NIGHT </TITLE>
<AFNAME> SYDNEY </AFNAME>
<ALNAME> SHELDON </ALNAME>
<PRICE> 10 </PRICE>
<QUANTITY> 100 </QUANTITY>
</BOOK>
<BOOK>
<TITLE> THE CLIENT </TITLE>
<AFNAME> JOHN </AFNAME>
<ALNAME> GRISHAM </ALNAME>
<PRICE> 20 </PRICE>
<QUANTITY> 250 </QUANTITY>
</BOOK>
<BOOK>
<TITLE> A STRANGER IN THE MIRROR </TITLE>
<AFNAME> SYDNEY </AFNAME>
<ALNAME> SHELDON </ALNAME>
<PRICE> 15 </PRICE>
<QUANTITY> 120 </QUANTITY>
</BOOK>
</BOOKDETAILS>

To display the above data in a tabular format, you can use the following style sheet:
8_P_1_a.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<table border="2">
<thead>
<th> TITLE </th>
<th> AUTHOR </th>
<th> PRICE </th>
<th> QUANTITY </th>
</thead><tbody>
<xsl:for-each select="BOOKDETAILS/BOOK">

44 eXtensible Markup Language ©NIIT


<tr>
<td><xsl:value-of select="TITLE"/> </td>
<td> <xsl:value-of select="AFNAME"/>
<xsl:text> </xsl:text>
<xsl:value-of select="ALNAME"/>
</td>
<td><xsl:value-of select="PRICE" /></td>
<td><xsl:value-of select="QUANTITY" /> </td>
</tr>
</xsl:for-each>
</tbody>
</table>
</xsl:template>
</xsl:stylesheet>
In the above code, the xsl:text element is used to add a space between the first name and last name
of an author.

To display the same book details in a list, you can use the following style sheet:
8_P_1_b.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<xsl:for-each select="BOOKDETAILS/BOOK">
<li>
TITLE: <xsl:value-of select="TITLE"/><br />
AUTHOR: <xsl:value-of select="AFNAME"/> <xsl:text> </xsl:text>
<xsl:value-of select="ALNAME"/> <br/>
PRICE: <xsl:value-of select="PRICE" /><br/>
QUANTITY: <xsl:value-of select="QUANTITY" /> <br/>
</li>
<hr />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
To accept user’s choice of the view, you need to create a Web page containing frames. The left frame
will display the controls for accepting user input and the right frame will be used for results. For
creating a blank page, you can use the following code:
right.htm
<html>
<head>
<title>Untitled Document</title>
</head>
<body bgcolor="#FFFFFF">
<div id="x">
</div>
</body>
</html>
The div block in the above code will be used to display the list or table containing book details.

You can use the following code for accepting user’s choice:
left.htm
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
<script language="javascript">

©NIIT eXtensible Markup Language 45


var xmlDoc
function loadXML()
{
xmlDoc = new ActiveXObject("Msxml2.DOMDocument.4.0");
xmlDoc.async = false;
xmlDoc.load("8_P_1.xml");
}

function ApplyXSL()
{
var xslt = new ActiveXObject("Msxml2.XSLTemplate.4.0");
var xslDoc = new
ActiveXObject("Msxml2.FreeThreadedDOMDocument.4.0");
var xslProc;
xslDoc.async = false;
alert (stylesheet.value);
xslDoc.load(stylesheet.value);
xslt.stylesheet = xslDoc;
xslProc = xslt.createProcessor();
xslProc.input = xmlDoc;
xslProc.transform();
parent.right.x.innerHTML=xslProc.output;
}

</script>

</head>
<body bgcolor="#FFFFFF" onLoad="loadXML()">
<select name="stylesheet" onChange="ApplyXSL()">
<option value="8_P_1_a.xsl"> View Book Details in a
Table </option>
<option value="8_P_1_b.xsl"> View Book Details in a
List </option>
</select>
</body>
</html>

The above code will display a drop-down list box for accepting user’s choice. As soon as the Web page
is loaded, the loadXML function is invoked. This function loads the XML document in a
DOMDocument object. When a user selects one of the options given in the drop-down list box, the
onchange event of the SELECT element is fired and the ApplyXSL function is called. This function
simply applies appropriate style sheet to the XML document.

Finally, you need to create the main page, which will be used to display left.htm and right.htm.
<HTML>
<HEAD>
<TITLE>XML/XSL Viewer Demo</TITLE>
</HEAD>
<FRAMESET COLS="200,*" FRAMEBORDER="0" BORDER="no"
FRAMESPACING="0">
<FRAME ID="left" SRC="left.htm" SCROLLING="no">
<FRAME ID="right" SRC="right.htm">
</FRAMESET>
</HTML>
To execute the complete code, open index.htm in the browser and select one of the options from the
drop-down list box.

46 eXtensible Markup Language ©NIIT


Solutions: Unguided Practice
UGP 1.
This file accepts the name of the XML file. It provides a text box and a submit hyperlink. On clicking
the hyperlink, javascript code loads the XML document. If the XML file is well formed then the
javascript function, extracts the elements whose node name is CUSTOMERNAME. The function then
loops through the list of nodes returned by the output and if the text enclosed in the elements is "Harold
Johnson", the function extracts the ADDRESS and the PHONENUMBER elements and sets the values
accordingly and displays the output in a message box.

XMLDisplayString.htm
<html>
<head>
<title>XML</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
</head>
<body bgcolor="#FFFFFF">
<form name="frmXMLFileName" method="post" action="">
<table width="60%" border="0">
<tr>
<td width="60%"><font face="Arial, Helvetica, sans-serif"
size="2">Enter the XML FileName Here
</font></td>
</tr>
<tr>
<td width="24%">
<input type="text" name="TxtName">
</td>
</tr>
<tr>
<td width="41%"><font size="2" face="Arial, Helvetica, sans-
serif">
<a href="#"
onclick="javascript:cmdSubmit_click()">Submit</a></font></td>
</tr>
</table>
</form>
<p align="left">&nbsp;</p>

<script Language="javascript">
function cmdSubmit_click()
{
var objelements;

if (frmXMLFileName.TxtName.value.length==0)
{
alert ("Invalid XML String");
}
else
{
var xmldoc= new ActiveXObject("Msxml2.DOMDocument.4.0");
xmldoc.load(frmXMLFileName.TxtName.value);
var error=xmldoc.parseError;
if(error!="")
{
alert("Error");

©NIIT eXtensible Markup Language 47


}
else
{
objelements=xmldoc.getElementsByTagName("CUSTOMERNAME");
for(ctr=0;ctr<=objelements.length;ctr++)
{
if (objelements[ctr].text=="Harold Johnson")
{

objelements=xmldoc.getElementsByTagName("ADR
ESS");
objelements[ctr].text="94, McFarlane
Avenue";

objelements=xmldoc.getElementsByTagName("PHO
NE");
objelements[ctr].text="412-233-2344";

alert(xmldoc.xml);
break;
}
}
}
}
}
</script>
</body>
</html>

Customer.xml
<?xml version="1.0"?>
<CUSTOMER>
<CUSTOMERNAME>Harold Johnson</CUSTOMERNAME>
<ADDRESS>56, Regent Road</ADDRESS>
<CITY>London</CITY>
<COUNTRY>UK</COUNTRY>
<PHONE>444-425-2355</PHONE>
</CUSTOMER>

UGP 2.
This file accepts the name of the XML file. It provides a text box and a submit hyperlink. Clicking the
hyperlinks uses dom and javascript to load the xml file. If the xml file is well formed then the JavaScript
function, loops through the entire set of nodes present in the xml document using the childNode
function and uses the nodeName, nodeType and nodeValue properties of DOMDocument class to
display the output in a message box.

XMLDisplayString.htm
<html>
<head>
<title>XML</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
</head>

<body bgcolor="#FFFFFF">
<form name="frmXMLFileName" method="post" action="">
<table width="60%" border="0">
<tr>

48 eXtensible Markup Language ©NIIT


<td width="60%"><font face="Arial, Helvetica, sans-serif"
size="2">Enter the XML FileName Here
</font></td>
</tr>
<tr>
<td width="24%">
<input type="text" name="TxtName">
</td>
</tr>
<tr>
<td width="41%"><font size="2" face="Arial, Helvetica,
sans-serif"><a href="#"
onclick="javascript:cmdSubmit_click()">Submit</a></font>
</td>
</tr>
</table>
</form>
<p align="left">&nbsp;</p>
<script Language="javascript">
function cmdSubmit_click()
{
var objelements;
if (frmXMLFileName.TxtName.value.length==0)
{
alert ("Invalid XML String");
}
else
{
var xmldoc= new ActiveXObject("Msxml2.DOMDocument.4.0");
xmldoc.load(frmXMLFileName.TxtName.value);

var error=xmldoc.parseError;
if(error!="")
{
alert("Error");
}
else
{
for(ctr=1;ctr<xmldoc.childNodes.length;ctr++)
{
alert("Node Name: " +
xmldoc.childNodes[ctr].nodeName);
alert("Node Type: " +
xmldoc.childNodes[ctr].nodeTypeString);

var objparentnode=xmldoc.childNodes[ctr];

for(ctr1=0;ctr1<objparentnode.childNodes.len
gth;ctr1++)
{

alert("Node Name: " +


objparentnode.childNodes[ctr1].nodeNam
e);

alert("Node Type: " +


objparentnode.childNodes[ctr1].nodeType
String);

var objchildnode =
objparentnode.childNodes[ctr1];

©NIIT eXtensible Markup Language 49


for(ctr2=0;ctr2<objchildnode.childNode
s.length;ctr2++)
{
alert("Node Value: " +
objchildnode.childNodes[ctr2].nodeValu
e);

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

movie.xml
<?xml version="1.0"?>
<MOVIE>
<MOVIEID>M920</MOVIEID>
<MOVIENAME>The Last Emperor</MOVIENAME>
<CAST>John Lone</CAST>
<DIRECTOR>Bernado Bertolucci</DIRECTOR>
<YEAROFRELEASE>1987</YEAROFRELEASE>
<CATEGORY>Drama</CATEGORY>
</MOVIE>

UGP 3.
The correct code for loading the emp.xml file and applying empss.xsl to it is as follows:
<html>
<script language="javascript">
var empt = new ActiveXObject("Msxml2.XSLTemplate.4.0");
var emptdoc = new
ActiveXObject("Msxml2.FreeThreadedDOMDocument.4.0");
var empproc;
emptdoc.async = false;
emptdoc.load("empss.xsl");
empt.stylesheet = emptdoc;
var empxml = new ActiveXObject("Msxml2.DOMDocument.4.0");
empxml.async = false;
empxml.load("emp.xml");
empproc = empt.createProcessor();
empproc.input = empxml;
empproc.transform();
alert(empproc.output);
</script>
</html>

50 eXtensible Markup Language ©NIIT


Solutions to Additional Exercises
1.

This solution to the given problem can be achieved using three files, two .xsd files and a .xml file.

The files required in the given scenario are as follows:

a. commonschema.xsd - This xsd file holds the schema of all the reusable components in the solution.

b. casehistory.xsd - This xsd file makes use of commonschema.xsd to define the schema for
casehistory.xml

c. casehistory.xml - This xml file has CASEHISTORY as the root element with an ID "C001". The
information in this xml file is grouped into two elements, PERSONALINFORMATION and
CASEINFORMATION. PERSONALINFORMATION stores the
NAME,ADDRESS,GENDER,AGE, and EXISTINGDISEASES of a patient. The
CASEINFORMATION stores every visit made by the patient to the hospital in the element
VISITINFORMATION. The VISITINFORMATION has
DATE,DOCTOR,COMPLAIN,DIAGNOSIS, PRESCRIPTION, and NEXTDATEOFVISIT.

All the above files are in the same namespace and hence include element is used to include the
definitions in commonschema.xsd in casehistory.xsd. Use the XML Schema Validator to validate the
xml file against its schema.
Casehistory.xml
<?xml version="1.0"?>
<pat1:CASEHISTORY xmlns:pat1="http://www.Getwellsoon.com/patient"
CASESHEETID="C001">
<PERSONALINFORMATION>
<NAME>John Watson</NAME>
<ADDRESS>
<HOUSENUMBER>24</HOUSENUMBER>
<STREET>Wellington Road</STREET>
<CITY>Seattle</CITY>
<STATE>Washington</STATE>
<ZIP>55555</ZIP>
</ADDRESS>
<GENDER>MALE</GENDER>
<AGE>10</AGE>
<EXISTINGDISEASES>Diabetes</EXISTINGDISEASES>
</PERSONALINFORMATION>
<CASEINFORMATION>
<VISITINFORMATION>
<DATE>2001-03-29</DATE>
<DOCTOR>Diane</DOCTOR>
<COMPLAIN>Injury to the left knee caused heavy
bleeding</COMPLAIN>
<DIAGNOSIS>hematoma in left knee</DIAGNOSIS>
<PRESCRIPTION>bed rest and change dressing twice a
week</PRESCRIPTION>
<NEXTDATEOFVISIT>2001-04-07</NEXTDATEOFVISIT>
</VISITINFORMATION>
<VISITINFORMATION>
<DATE>2001-04-07</DATE>
<DOCTOR>Diane</DOCTOR>
<COMPLAIN>Injury to the left knee caused heavy

©NIIT eXtensible Markup Language 51


bleeding</COMPLAIN>
<DIAGNOSIS>hematoma in left knee</DIAGNOSIS>
<PRESCRIPTION>bed rest and change dressing twice a
week</PRESCRIPTION>
<NEXTDATEOFVISIT>2001-04-14</NEXTDATEOFVISIT>
</VISITINFORMATION>
</CASEINFORMATION>
</pat1:CASEHISTORY>

Casehistory.xsd
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.Getwellsoon.com/patient"
xmlns:pat="http://www.Getwellsoon.com/patient">
<include schemaLocation="commoninfo.xsd"/>
<element name="CASEHISTORY">
<complexType>
<sequence>
<element name="PERSONALINFORMATION"
type="pat:dtpersonaldata"/>
<element name="CASEINFORMATION"
type="pat:dtcasedata"/>
</sequence>
<attribute name="CASESHEETID" type="pat:dtcasesheetid"/>
</complexType>
</element>
<complexType name="dtpersonaldata">
<sequence>
<element name="NAME" type="string"/>
<element name="ADDRESS" type="pat:dtaddress"/>
<element name="GENDER" type="pat:dtgender"/>
<element name="AGE" type="positiveInteger"/>
<element name="EXISTINGDISEASES"
type="string"/>
</sequence>
</complexType>
<complexType name="dtcasedata">
<sequence>
<element name="VISITINFORMATION"
type="pat:dtdateofvisit" maxOccurs="unbounded"/>
</sequence>
</complexType>
<complexType name="dtdateofvisit">
<sequence>
<element name="DATE" type="date"/>
<element name="DOCTOR" type="string"/>
<element name="COMPLAIN" type="string"/>
<element name="DIAGNOSIS" type="string"/>
<element name="PRESCRIPTION" type="string"/>
<element name="NEXTDATEOFVISIT" type="date"/>
</sequence>
</complexType>
</schema>

52 eXtensible Markup Language ©NIIT


Commoninfo.xsd
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.Getwellsoon.com/patient"
xmlns:pat="http://www.Getwellsoon.com/patient">
<simpleType name="dtcasesheetid">
<restriction base="string">
<pattern value="[C]\d{3}"/>
</restriction>
</simpleType>
<complexType name="dtaddress">
<sequence>
<element name="HOUSENUMBER" type="string"/>
<element name="STREET" type="string"/>
<element name="CITY" type="string"/>
<element name="STATE" type="string"/>
<element name="ZIP" type="decimal"/>
</sequence>
</complexType>
<simpleType name="dtgender">
<restriction base="string">
<pattern value="(MALE|FEMALE)"/>
</restriction>
</simpleType>
</schema>

2.

The solution to the given scenario can be achieved using 2 files. Two xsd files and a xml file.

The xsd files are:

a. casehistory.xsl - This xsl file holds the transformation information to display the xml file.

b. casehistory.xml - This xml file has CASEHISTORY as the root element with an ID "C001". The
information in this xml file is grouped into two elements - PERSONALINFORMATION and
CASEINFORMATION. The PERSONALINFORMATION stores the
NAME,ADDRESS,GENDER,AGE, and EXISTINGDISEASES. The CASEINFORMATION stores
every visit made by the patient to the hospital in the element VISITINFORMATION. The
VISITINFORMATION has DATE,DOCTOR,COMPLAIN,DIAGNOSIS, PRESCRIPTION, and
NEXTDATEOFVISIT.
The xsl file displays the personal information of the patient in a list and the case related information in a
table. Every visit of the patient to the doctor is displayed in a row along with all the information of the
patients visit.

Casehistory.xml
<?xml version="1.0"?>
<?xml:stylesheet type="text/xsl" href="casehistory.xsl"?>
<CASEHISTORY CASESHEETID="C001">
<PERSONALINFORMATION>
<NAME>John Watson</NAME>
<ADDRESS>
<HOUSENUMBER>24</HOUSENUMBER>
<STREET>Wellington Road</STREET>
<CITY>Seattle</CITY>
<STATE>Washington</STATE>
<ZIP>55555</ZIP>
</ADDRESS>

©NIIT eXtensible Markup Language 53


<GENDER>MALE</GENDER>
<AGE>10</AGE>
<EXISTINGDISEASES>Diabetes</EXISTINGDISEASES>
</PERSONALINFORMATION>
<CASEINFORMATION>
<VISITINFORMATION>
<DATE>2001-03-29</DATE>
<DOCTOR>Diane</DOCTOR>
<COMPLAIN>Injury to the left knee caused
heavy bleeding</COMPLAIN>
<DIAGNOSIS>hematoma in left knee</DIAGNOSIS>
<PRESCRIPTION>bed rest and change dressing
twice a week</PRESCRIPTION>
<NEXTDATEOFVISIT>2001-04-07</NEXTDATEOFVISIT>
</VISITINFORMATION>
<VISITINFORMATION>
<DATE>2001-04-07</DATE>
<DOCTOR>Diane</DOCTOR>
<COMPLAIN>Injury to the left knee caused
heavy bleeding</COMPLAIN>
<DIAGNOSIS>hematoma in left knee</DIAGNOSIS>
<PRESCRIPTION>bed rest and change dressing
twice a week</PRESCRIPTION>
<NEXTDATEOFVISIT>2001-04-14</NEXTDATEOFVISIT>
</VISITINFORMATION>
</CASEINFORMATION>
</CASEHISTORY>

casehistory.xsl
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="/">
<xsl:apply-templates />,
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="EXISTINGDISEASES">
<xsl:if test="position()=last()”>
.
</xsl:if>
</xsl:template>
<xsl:template match="/">
<HTML>
<HEAD>
<TITLE>Patient Information System</TITLE>
</HEAD>
<BODY>
<H1>Case History</H1>
<xsl:for-each select="CASEHISTORY/PERSONALINFORMATION">

<B>Name:</B> <xsl:value-of select="NAME"/><br/>


<B>Address:</B><br/>
HouseNumber: <xsl:value-of
select="ADDRESS/HOUSENUMBER" /><br/>
Street:<xsl:value-of select="ADDRESS/STREET" /><br/>

54 eXtensible Markup Language ©NIIT


City:<xsl:value-of select="ADDRESS/CITY" /><br/>
State:<xsl:value-of select="ADDRESS/STATE" /><br/>
Zip:<xsl:value-of select="ADDRESS/ZIP" /><br/>

<B>Gender: </B><xsl:value-of select="GENDER" /><br/>


<B>Age:</B> <xsl:value-of select="AGE"
/><br/>
<B>Existing Diseases:</B> <xsl:apply-templates
select="EXISTINGDISEASES" />
</xsl:for-each>
<p/>
<table border ="2">
<tr>
<td>
<b>Date</b>
</td>
<td><b>Doctor</b></td>
<td><b>Complain</b></td>
<td><b>Diagnosis</b></td>
<td><b>Prescription</b></td>
<td><b>Next Date of Visit</b></td>
</tr>
<xsl:for-each
select="CASEHISTORY/CASEINFORMATION/VISITINFORMATION">
<tr>
<td>
<xsl:value-of select="DATE"/>
</td>
<td>
<xsl:value-of select="DOCTOR"/>
</td>
<td><xsl:value-of select="COMPLAIN"/></td>
<td><xsl:value-of select="DIAGNOSIS"/></td>
<td><xsl:value-of select="PRESCRIPTION"/></td>
<td><xsl:value-of select="NEXTDATEOFVISIT"/></td>
</tr>
</xsl:for-each>
</table>
</BODY>
</HTML>
</xsl:template>
</xsl:stylesheet>

3.

The solution to the given problem can be achieved using the xmldisplay.htm file. This html file
displays a form that contains a text field and a hyperlink. The text field accepts the name of the xml file
and clicking on the link invokes a function called cmdsubmit_click.

This function is written using JavaScript. This JavaScript function instantiates the DOMDocument.4.0
class and obtains the reference of the object in to a variable xmldoc. Using the load(filename) method of
DOMDocument class, the JavaScript function loads the xml file and using the xml property of the
DOMDocument class displays the content of the xml file in a message box.

©NIIT eXtensible Markup Language 55


trial.xml
<?xml version="1.0"?>
<PEOPLEDETAILS>
<NAME>John</NAME>
<NAME>John</NAME>
<NAME>John</NAME>
<NAME>John</NAME>
<NAME>John</NAME>
</PEOPLEDETAILS>

XMLDisplay.htm
<html>
<head>
<title>XML</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
</head>
<body bgcolor="#FFFFFF">
<form name="frmPatient" method="post" action="">
<table width="41%" border="0">
<tr>
<td width="45%"><font face="Arial, Helvetica, sans-serif"
size="2">Name
of the XML File</font></td>
<td width="24%">
<input type="text" name="TxtName">
</td>
<td width="41%"><font size="2" face="Arial, Helvetica,
sans-serif"><a href="#"
onclick="javascript:cmdSubmit_click()">Submit</a></font></td>
</tr>
</table>
</form>
<p align="left">&nbsp;</p>
<script Language="javascript">
function cmdSubmit_click()
{if (frmPatient.TxtName.value.length==0)
{
alert ("Invalid File Name");
}
else
{
var xmldoc= new ActiveXObject("Msxml2.DOMDocument.4.0");

xmldoc.load(frmPatient.TxtName.value);
var error=xmldoc.parseError;
if(error!="")
{
alert("error");
}
else{
alert(xmldoc.xml);
}
}
}
</script>
</body>
</html>

56 eXtensible Markup Language ©NIIT


4.

You can create an HTML file to display a form that contains a text area and a hyperlink. The text area
accepts a string from the user. This string is then validated for its conformance as a well-formed xml.
The user needs to click the submit hyperlink to check it.

The onclick event of the hyperlink is processed using a function written in JavaScript. This JavaScript
function instantiates the DOMDocument.4.0 class and obtains the reference of the object in to a variable
xmldoc. Using the loadxml(string) method of DOMDocument class, the JavaScript function loads the
string entered by the user. Using the parseError property of the DOMDocument class, the information
about any errors in the xml document is retrieved into a variable called error. If there is no error, then
the JavaScript function displays the entire string by using the xml property of the DOMDocument, else
the JavaScript function displays error.
<html>
<head>
<title>XML</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
</head>
<body bgcolor="#FFFFFF">
<form name="frmPatient" method="post" action="">
<table width="60%" border="0">
<tr>
<td width="60%"><font face="Arial, Helvetica, sans-serif"
size="2">Enter the XML String Here
</font></td>
</tr>
<tr>
<td width="24%">
<TEXTAREA cols=70 name=TxtName rows=20></TEXTAREA>
</td>
</tr>
<tr>
<td width="41%"><font size="2" face="Arial, Helvetica,
sans-serif"><a href="#"
onclick="javascript:cmdSubmit_click()">Submit</a></font></td>
</tr>
</table>
</form>
<p align="left">&nbsp;</p>
<script Language="javascript">
function cmdSubmit_click()
{
if (frmPatient.TxtName.value.length==0)
{
alert ("Invalid XML String");
}
else
{
var xmldoc= new ActiveXObject("Msxml2.DOMDocument.4.0");

xmldoc.loadXML(frmPatient.TxtName.value);
var error=xmldoc.parseError;
if(error!="")
{
alert("error");
}
else
{

©NIIT eXtensible Markup Language 57


alert(xmldoc.xml);
}
}
}
</script>
</body></html>
5.

To create a text area for accepting XML tags, you need to create a Web page. The Web page displays a
form that contains a text area and a hyperlink. The text area accepts a string from the user. This string is
then validated for its conformance as a well-formed xml. The user needs to click the submit hyperlink to
check it.

The onclick event of the hyperlink is handled using a JavaScript function. This function instantiates the
DOMDocument.4.0 class and obtains the reference of the object in to a variable xmldoc. Using the
loadxml(string) method of DOMDocument class, the JavaScript function loads the string entered by the
user. Using the parseError property of the DOMDocument class, the information about any errors in the
xml document is retrieved into a variable called error. If there is no error, a new element called
“WELLFORMED” is created using the createElement(elementname) of the DOMDocument class.
Using the documentElement property of the DOMDocument class, the JavaScript function obtains
reference to root element of the xml document into a variable called rootnode. The JavaScript function
then invokes the appendChild(elementname) function to attach the node to the root element. Using the
text property of a node, the JavaScript function sets the text as good for the WELLFORMED element.
The JavaScript function then sets the text of the textarea to the new xml string.
<! --- XMLDisplayStringNewNode.htm -- >
<html>
<head>
<title>XML</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
</head>
<body bgcolor="#FFFFFF">
<form name="frmPatient" method="post" action="">
<table width="60%" border="0">
<tr>
<td width="60%"><font face="Arial, Helvetica, sans-serif"
size="2">Enter the XML String Here
</font></td>
</tr>
<tr>
<td width="24%">
<TEXTAREA cols=70 name=TxtName rows=20></TEXTAREA>
</td>
</tr>
<tr>
<td width="41%"><font size="2" face="Arial, Helvetica, sans-
serif"><a href="#"
onclick="javascript:cmdSubmit_click()">Submit</a></font></td>
</tr>
</table>
</form>
<p align="left">&nbsp;</p>
<script Language="javascript">
function cmdSubmit_click()
{
var newelement;
var rootnode;
if (frmPatient.TxtName.value.length==0)
{
alert ("Invalid XML String");

58 eXtensible Markup Language ©NIIT


}
else
{
var xmldoc= new ActiveXObject("Msxml2.DOMDocument.4.0");

xmldoc.loadXML(frmPatient.TxtName.value);
var error=xmldoc.parseError;
if(error!="")
{
alert("error");
}
else
{
rootnode=xmldoc.documentElement;
newelement=xmldoc.createElement("WELLFORMED");

rootnode.appendChild(newelement);
rootnode.lastChild.text = "good";
frmPatient.TxtName.value=xmldoc.xml
}
}
}
</script>
</body>
</html>

6.

You can create an HTML file to display a form that contains a text area and a hyperlink. The text area
accepts a string from the user. This string is then validated for its conformance as a well-formed xml.
The user needs to click the submit hyperlink to check it. The code for creating the HTML page is given
below:
<html>
<head>
<title>XML</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
</head>
<body bgcolor="#FFFFFF">
<form name="frmPatient" method="post" action="">
<table width="60%" border="0">
<tr>
<td width="60%"><font face="Arial, Helvetica, sans-serif"
size="2">Enter the XML String Here
</font></td>
</tr>
<tr>
<td width="24%">
<TEXTAREA cols=70 name=TxtName rows=20></TEXTAREA>
</td>
</tr>
<tr>
<td width="41%"><font size="2" face="Arial, Helvetica, sans-
serif"><a href="#"
onclick="javascript:cmdSubmit_click()">Submit</a></font></td>

©NIIT eXtensible Markup Language 59


</tr>
<tr>
<td width="41%"><font size="2" face="Arial, Helvetica, sans-
serif"><a href="#"
onclick="javascript:cmdReset_click()">Reset</a></font></td>
</tr>
</table>
</form>
<p align="left">&nbsp;</p>
<script Language="javascript">
function cmdSubmit_click()
{
var newelement;
var rootnode;
if (frmPatient.TxtName.value.length==0)
{
alert ("Invalid XML String");
}
else
{
var xmldoc= new ActiveXObject("Msxml2.DOMDocument.4.0");

xmldoc.loadXML(frmPatient.TxtName.value);
var error=xmldoc.parseError;
if(error!="")
{
alert("error");
}
else
{
rootnode=xmldoc.documentElement;
newelement=xmldoc.createElement("WELLFORMED");

rootnode.appendChild(newelement);
rootnode.lastChild.text = "good";
frmPatient.TxtName.value=xmldoc.xml
}
}
}
function cmdReset_click()
{
var deleteelements;
var rootnode;
if (frmPatient.TxtName.value.length==0)
{
alert ("Invalid XML String");
}
else
{
var xmldoc= new ActiveXObject("Msxml2.DOMDocument.4.0");

xmldoc.loadXML(frmPatient.TxtName.value);
var error=xmldoc.parseError;
if(error!="")
{
alert("error");
}
else

60 eXtensible Markup Language ©NIIT


{
rootnode=xmldoc.documentElement;

deleteelements=xmldoc.getElementsByTagName("WELLFORMED");

for (var ctr=0; ctr<deleteelements.length; ctr++)


{
rootnode.removeChild(deleteelements.item(ctr));
} frmPatient.TxtName.value=xmldoc.xml

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

In the above HTML page, the onclick event of the hyperlink is handled by a function written in
JavaScript. This function instantiates the DOMDocument.4.0 class and obtains the reference of the
object in to a variable xmldoc. Using the loadxml(string) method of DOMDocument class, the
JavaScript function loads the string entered by the user. Using the parseError property of the
DOMDocument class, the information about any errors in the xml document is retrieved into a variable
called error. If there is no error then the JavaScript function creates a new element using the
createElement(elementname) of the DOMDocument class creates a element named WELLFORMED.
Using the documentElement property of the DOMDocument class, the JavaScript function obtains
reference to root element of the xml document into a variable called rootnode. The JavaScript function
then invokes the appendChild(elementname) function to attach the node to the root element. Using the
text property of a node, the JavaScript function sets the text as good for the WELLFORMED element.
The JavaScript function then sets the text of the textarea to the new xml string.

This html page also provides another hyperlink called Reset. Clicking on this link, gets the list of nodes
named WELLFORMED. The JavaScript function uses getElementsbyTagName(elementname) of the
DOMDocument class. The JavaScript function then loops through the number of elements returned by
the function and uses the removeChild function to remove the nodes. The JavaScript function then sets
the text of the textarea to the new xml string.

7.

The following XSLT style sheet can be used to display the average student.xsl - This XSLT style sheet
uses XPath language to calculate the sum of marks obtained by the student in maths, socialstudies and
science and divides it by 3 to get the average marks.

Use the html file required to transform xpath/xsl/t syntax.

<! -- student.xsl -- >

<?xml version='1.0'?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">

<xsl:template match="/">

<p align="center"><font color="blue">STUDENT


DETAILS</font></p>

<B>STUDENT ID:</B> <xsl:value-of


select="MARKSSUMMARY/STUDENT/@ID"/> <br/>

©NIIT eXtensible Markup Language 61


Maths Total: <xsl:value-of
select='sum(//MARKSSUMMARY/STUDENT/TEST/MATHS) div 3'/> <br/>

Science Total:<xsl:value-of
select='sum(//MARKSSUMMARY/STUDENT/TEST/SCIENCE) div 3'/><br/>

Social Total:<xsl:value-of
select='sum(//MARKSSUMMARY/STUDENT/TEST/SOCIALSTUDIES) div
3'/><br/>

</xsl:template>

</xsl:stylesheet>

<! -- student.xml -- >


<?xml version="1.0" ?>
<?xml:stylesheet type="text/xsl" href="student.xsl"?>
<MARKSSUMMARY>
<STUDENT ID="S001">
<TEST SCHEME="QUARTERLY">
<MATHS>90</MATHS>
<SCIENCE>100</SCIENCE>
<SOCIALSTUDIES>90</SOCIALSTUDIES>
</TEST>
<TEST SCHEME="HALFYEARLY">
<MATHS>80</MATHS>
<SCIENCE>60</SCIENCE>
<SOCIALSTUDIES>75</SOCIALSTUDIES>
</TEST>
<TEST SCHEME="FINAL">
<MATHS>70</MATHS>
<SCIENCE>70</SCIENCE>
<SOCIALSTUDIES>45</SOCIALSTUDIES>
</TEST>
</STUDENT>
</MARKSSUMMARY>
8. The languages for defining the structure of an xml document are DTD and XSD.

9. Which of the following is true?

a. Simple Data types contain elements –false

b. Complex data types contain elements, and attributes – true

10. An object model that allows scripting languages to access and manipulate XML documents is
known as Document Object Model.

62 eXtensible Markup Language ©NIIT


ADDITIONAL BOOK REFERENCES
Erik .T Ray, Learning XML

Steven Holzner, Inside XML

Elliotte Rusty Harold, W. Scott Means, XML in a Nutshell: A Desktop Quick Reference

John Duckett, Professional XML Schemas

John Griffin, XML and SQL Server 2000

John Robert Gardner, Zarella .L Rendon, XSLT and XPATH: A Guide to XML Transformations

Elliotte Rusty Harold, XML Bible

Kurt Cagle, Beginning XML

Mark Birbeck, Professional XML

Paul .J Burke, Professional SQL Server 200 XML

Paul Deitel, The Complete XML Training Course

Graeme Malcom, Programming Microsoft SQL Server 2000 with XML

Dave Mercer, XML: A Beginner's Guide

Michael .J Young, Step by Step XML

James Bean, XML Globalization and Best Practices: Using XML Schemas and XML Data

©NIIT eXtensible Markup Language 63


LIST OF WEB SITES
„Welcome to XML Spy! –
http://www.xmlspy.com/

„IONA XMLBUS –
http://www.xmlbus.com/

„XML From the Inside Out –


http://www.xml.com/

„Extensible Markup Language –


http://www.w3.org/XML/

„Java ™ Technology & XML –


http://java.sun.com/xml/

„DevX: XML Zone-


http://www.xml-zone.com/default1.asp?Area=XML

„XML Tutorial –
http://www.w3schools.com/xml/default.asp

„WDVL: XML: Extensible Markup Language –


http://wdvl.internet.com/Authoring/Languages/XML/

„Downloadable Java-based Applications –


http://www.ibm.com/java/apps/

„Welcome to the Apache XML Project -


http://xml.apache.org/

„DeveloperWorks: XML –
http://www-106.ibm.com/developerworks/xml/

„expat - XML Parser Toolkit –


http://www.jclark.com/xml/expat.html

„XML Global Technologies - Consulting –


http://www.xmlglobal.com/consult/

64 eXtensible Markup Language ©NIIT


„XML Magazine –
http://www.xmlmag.com/

„WebDeveloper.com -
http://www.webdeveloper.com/xml/

„Project Cool XML Zone –


http://www.projectcool.com/developer/xmlz/

„Xmlpitstop.com –
http://www.xmlpitstop.com/

„XML Script – XML Productivity Applications –


http://www.xmlscript.org/

„Introduction to DSSSL –
http://www.prescod.net/dsssl/

„The XML Cover Pages DSSSL - Document Style Semantics and Specification Language. ISO/IEC
10179:1996 –

http://www.oasis-open.org/cover/dsssl.html

„DSSSL Document Style Sheet Semantics and Specification Language -


http://www.netfolder.com/DSSSL/

„SUN XML | FAQs

http://www.sun.com/software/xml/faqs.html;$sessionid$BBTWYAIAAABJHAMTA1FU3NQ

©NIIT eXtensible Markup Language 65


SESSION PLAN: EXTENSIBLE MARKUP LANGUAGE
Cycle # Activity/Problem No. Duration (In Mins)
Cycle1
OCR1
Lesson 1: Objectives 5
EDI and XML 45
Components of XML 45
document
1.P.1 20
Summary 5
Total 120
OCR2
Lesson 2: Objectives 5
Using DTD 50
JAM 10
Using schemas 20
2.P.1 25
Summary 10
Total 120
Cycle2
OCR1
Lesson 3: Objectives 2
Attributes in schema 40
JAM 10
Using namespaces 10
Importing schemas 25
JAM 10
Summary 8
Total 105
OCR2
Lesson 4: Objectives 5
Create groups of elements 30
and attributes in an XML
schema
JAM 10
4.P.2 60
Summary 5
Total 110
Cycle3
OCR1
Lesson 5: Objectives 5
CSS 20
JAM 10
XSLT 45
5.P.1 20
Summary 10
Total 110
OCR2
Lesson 6: Objectives 5
Conditional formatting 15

66 eXtensible Markup Language ©NIIT


JAM 10
XPath 40
HTML in XSL/T 20
6.P.1 20
Nested style sheets 5
Summary 5
Total 120
Cycle 4 OCR1
Lesson 7: Objectives 5
Introducing XML DOM 60
7.D.1 20
JAM 10
Summary 5
Total 100
OCR2
Lesson 8: Objectives 5
Validating an XML document 25
against schema
JAM 5
Dynamically applying style 25
sheets
8.P.1 40
Summary 5
Total 105

©NIIT eXtensible Markup Language 67

Вам также может понравиться