0% found this document useful (0 votes)
15 views129 pages

Unit 3

Uploaded by

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

Unit 3

Uploaded by

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

EXt ibl Markup

EXtensible M k Language
L
9XML was developed by the SGML Editorial Board of the
W ld Wide
World Wid Web
W b Consortium
C ti (W3C)

9The initial XML draft was ppresented in 1996 at a


conference in Boston. The official W3C specification (XML
1.0) was presented in 1998

What is XML?

9XML stands for EXtensible Markup Language

9XML is a markup language much like HTML

9XML was designed to carry data, not to display data


9XML tags are not predefined. You must define your own
tags

9XML is designed to be self-descriptive

9XML is a platform and application independent

The Difference Between XML and HTML


9XML was designed to transport and store data, with focus
on what data is

9HTML
HTML was designed to display data, with focus on how
data looks

9HTML is about displaying information, while XML is


about carrying information.
XML Does not DO Anything

9Maybe it is a little hard to understand,


understand but XML does not
DO anything

9XML was created to structure, store, and transport


information

9The following example is a note to Tove from Jani, stored


as XML:
XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
g g
<body>Don't forget me this weekend!</body>
</note>
9The note above is quite self descriptive. It has sender and
receiver information,, it also has a headingg and a message
g
body

9It is just pure information wrapped in tags. Someone must


write a piece of software to send, receive or display it.

XML is Just Plain Text

9XML is nothing special. It is just plain text. Software that


can handle plain text can also handle XML

9However, XML-aware applications can handle the XML


tags specially
specially. The functional meaning of the tags depends
on the nature of the application.
With XML You Invent Your Own Tags

9The tags in the previous example (like <to> and <from>)


are not defined in any XML standard.
standard These tags are
"invented" by the author of the XML document

9That is because the XML language has no predefined tags

9The tags usedd in


9Th i HTML (and
( d the
h structure off HTML) are
predefined. HTML documents can only use tags defined in
the HTML standard (like <p>,
<p> <h1>,
<h1> etc.)
etc )

9XML allows the author to define his own tags


g and his own
document structure
XML Separates Data from HTML

9If you need to display dynamic data in your HTML


document, it will take a lot of work to edit the HTML each
ti the
time th data
d t changes
h

9With
With XML
XML, data can be stored in separate XML files.
files This
way you can concentrate on using HTML for layout and
display, and be sure that changes in the underlying data will
not require any changes to the HTML

9Withh a few
9Wi f lines
li off JavaScript,
J S i you can readd an externall
XML file and update the data content of your HTML
XML Simplifies Data Sharing

9In the real world


world, computer systems and databases contain
data in incompatible formats

9XML data is stored in plain text format. This provides a


software- and hardware-independent way of storing data.
This makes it much easier to create data that different
applications can share

XML Simplifies Data Transport

9With XML, data can easily be exchanged between


incompatible systems.

9One of the most time-consuming challenges for


developers is to exchange data between incompatible
systems
y over the Internet

9Exchanging data as XML greatly reduces this complexity,


since the data can be read by different incompatible
applications

XML is Used to Create New Internet Languages

9A lot of new Internet languages are created with XML

Here are some examples:


H l
9XHTML the latest version of HTML

9WSDL for describing available web services


9WAP and WML as markup languages for handheld
devices

9RSS languages for news feeds

9RDF and OWL for describing resources and ontology

9SMIL for describing multimedia for the web

XML Tree

9XML documents form a tree structure that starts at "the


root" and branches to "the leaves"
An Example XML Document
9XML documents use a self-describingg and simple
p syntax:
y

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't
y forget
g me this weekend!</body>
y
</note>

9The first line is the XML declaration. It defines the XML


version (1.0) and the encoding used (ISO-8859-1 = Latin-
1/West European character set)
9The next line describes the root element of the document
((like saying:
y g "this document is a note"):
) <note>

9The next 4 lines describe 4 child elements of the root (to,


from, heading, and body):

<to>Tove</to>
<t >T </t >
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>

9And finally the last line defines the end of the root
element: </note>
XML Documents Form a Tree Structure

9XML documents must contain a root element


element. This
element is "the parent" of all other elements

9The elements in an XML document form a document tree

9The tree starts at the root and branches to the lowest level
of the tree

9All elements can have sub elements (child elements):


<root>
<child>
<subchild>.....</subchild>
</child>
</root>
9The terms parent, child, and sibling are used to describe
the relationships between elements

9Parent elements have children. Children on the same level


are called siblings (brothers or sisters)

9All
All elements can have text content and attributes (just like
in HTML)
Example
9The root element in the follwing example is <bookstore>

9All <book> elements in the document are contained within


<bookstore>

9The <book> element has 4 children: <title>,< author>,


<year>, <price>
<bookstore>
<book category="COOKING">
<title
title lang
lang="en">EverydayItalian</title>
en EverydayItalian /title
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30 00</price>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang
lang="en">Harry
en >Harry Potter</title>
<author>J K.Rowling</author>
<year>2005</year>
<price>29 99</price>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
< i >39 95</ i >
<price>39.95</price>
</book>
</bookstore>
XML Syntax Rules

9All XML Elements Must Have a Closing Tag


<p>This is a paragraph</p>

9XML Tags are Case Sensitive


--Opening and closing tags must be written with the
same case:
<Message>This is incorrect</message>
<
<message>This
>Thi is
i correct</message>
t</ >

9XML Elements Must be Properly Nested


<b><i>This text is bold and italic</i></b>
"Properly
p y nested" simply
p y means that since the <i>
element is opened inside the <b> element, it must be closed
inside the <b> element
9XML Documents Must Have a Root Element
<root>
<child>
<subchild>.....</subchild>
</child>
/ hild
</root>

9XML Attribute Values Must be Quoted


<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
Entity References

9There are 5 predefined entity references in XML:


&lt; < less than
&gt; > greater than
&amp; & ampersand
&
&apos; ' apostrophe
t h
&quot; " quotation mark

<message>if salary &lt; 1000 then</message> will output:


if salary < 1000 then

Comments in XML
9The syntax for writing comments in XML is similar to
that of HTML
<!-- This is a comment -->
White-space is Preserved in XML

9HTML truncates multiple white-space characters to one


single white-space:
HTML
HTML: Hello
H ll my name isi Tove
T
Output: Hello my name is Tove

9With XML, the white-space in a document is not truncated


XML Elements

9An XML element is everythingy g from (including)


( g) the
element's start tag to (including) the element's end tag

9An element
9 l can contain
i other
h elements,
l simple
i l text or a
mixture of both. Elements can also have attributes
XML Naming Rules

9Names can contain letters, numbers, and other characters

9Names cannott start


9N t t with
ith a number
b or punctuation
t ti
character

9Names cannot start with the letters xml (or XML, or Xml,
etc)

9Names cannot contain spaces

9Any name can be used, no words are reserved


Best Naming Practices

9Make names descriptive


<first_name>, <last_name>

9Names should be short and simple, like this: <book_title>


not like this: <the_title_of_the_book>

XML Elements are Extensible

9XML elements can be extended to carry more information


Example
<note>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>
9Let's imagine that we created an application that extracted
the <to>,, <from>,, and <body>y elements from the XML
document to produce this output:
MESSAGE
To: Tove
From: Jani
D 't fforgett me this
Don't thi weekend!
k d!

9Imagine
Imagine that the author of the XML document added some
extra information to it:
<note>
<date>2008-01-10</date>
<to>Tove</to>
<from>Jani</from>
f J i /f
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

9Should the application break or crash?


No. The application should still be able to find the
<to>, <from>, and <body> elements in the XML document
and
d produce
d the
th same output
t t

9One
One of the beauties of XML,
XML is that it can often be
extended without breaking applications

XML Attributes

9XML elements can have attributes in the start tag,


tag just like
HTML
9Attributes provide additional information about elements

XML Elements vs. Attributes

9T k a look
9Take l k at these
h examples:
l
Example1 <person gender="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
p

Example2 <person>
<gender>female</gender>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
9In the first example gender is an attribute

9In the next example, gender is an element

9Both examples provide the same information

9There are no rules about when to use attributes and when


to use elements

9Attributes are handy in HTML

9In XML , advice is to avoid them. Use elements instead


XML Attributes for Metadata

9Sometimes ID references are assigned to elements. These


IDs can be used to identify XML elements
E
Example
l
<messages>
<note id="501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="502">
<to>Jani</to>
<from>Tove</from>
<heading>Re:
g Reminder</heading>
g
<body>I will not</body>
</note>
</messages>
9The ID above is just an identifier, to identify the different
notes. It is not a ppart of the note itself

9So metadata (data about data) should be stored as


attributes, and that data itself should be stored as elements

Well Formed XML Documents

9A "Well Formed" XML document has correct XML syntax


Valid XML Documents

9A "Valid" XML document is a "Well Formed" XML


document, which also conforms to the rules of a Document
T
Type Definition
D fi iti (DTD)
(DTD):

<?xml version
version="11.00" encoding
encoding="ISO-8859-1"?>
ISO 8859 1 ?>
<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
h di R i d /h di
<body>Don't forget me this weekend!</body>
</note>
9The DOCTYPE declaration in the example above, is a
reference to an external DTD file.
file The content of the file is
shown below

<!DOCTYPE note
[
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT
!ELEMENT from
f (#PCDATA)>
(#PCDATA)
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
Introduction to DTD

9A Document Type Definition (DTD) defines the structure


of an XML document with a list of legal elements and
attributes
ib

9A DTD can be declared inside an XML document,


document or as an
external reference

Internal DTD Declaration

9If the DTD is declared inside the XML file,


file it should be
wrapped in a DOCTYPE definition with the following
syntax:
<!DOCTYPE root-element [element-declarations]>
Example XML document with an internal DTD:
<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT
!ELEMENT to (#PCDATA)>
(#PCDATA)
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend</body>
</note>
The DTD above is interpreted like this:

9!DOCTYPE note defines that the root element of this


document is note
9!ELEMENT note defines that the note element contains
four elements: "to, from, heading, body"
9!ELEMENT to defines
d fi the
th to
t element
l t to
t be
b off type
t
"#PCDATA"
9!ELEMENT
!ELEMENT from defines the from element to be of type
"#PCDATA"
9!ELEMENT heading defines the heading element to be
of type "#PCDATA"
9!ELEMENT body defines the body element to be of type
"#PCDATA"
External DTD Declaration

If the DTD is declared in an external file, it should be


wrapped in a DOCTYPE definition with the following
syntax:
t
<!DOCTYPE root-element SYSTEM "filename">

Example XML document with an external DTD:


<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
heading Reminder /heading
<body>Don't forget me this weekend!</body>
</note>
And this is the file "note.dtd" which contains the DTD:
<!ELEMENT note ((to, from, heading,
g body)>
y)
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT
!ELEMENT heading
h di (#PCDATA)>
(#PCDATA)
<!ELEMENT body (#PCDATA)>

Why Use a DTD?

9Withh a DTD,
9Wi DTD eachh off your XML files
fil can carry a
description of its own format

9With a DTD, independent groups of people can agree to


use a standard DTD for interchanging
g g data
9Your application can use a standard DTD to verify that the
data y
you receive from the outside world is valid

9You can also use a DTD to verify your own data

The Building Blocks of XML Documents

9The main building blocks of both XML and HTML


documents are elements

9Seen from a DTD point of view, all XML documents are


made up by the following building blocks:
™Elements
™Attributes
™Entities
™PCDATA
™CDATA

PCDATA
9PCDATA means parsed character data

9Think of character data as the text found between the start


tag and the end tag of an XML element

9PCDATA is text that WILL be parsed by a parser. The text


will be examined by the parser for entities and markup

9Tags
Tags inside the text will be treated as markup and entities
will be expanded
9However, parsed character data should not contain any &,
<,, or > characters;; these need to be represented
p byy the
&amp; &lt; and &gt; entities, respectively

CDATA
9CDATA means character data

9CDATA is text that will NOT be parsed by a parser. Tags


inside the text will NOT be treated as markupp and entities
will not be expanded

DTD – Elements
9In a DTD, elements are declared with an ELEMENT
declaration
Declaring Elements
9In a DTD, XML elements are declared with an element
declaration with the following syntax:
<!ELEMENT element-name category>
or
<!ELEMENT element-name (element-content)>

Empty Elements
9Empty elements are declared with the category keyword
EMPTY:
<!ELEMENT element-name EMPTY>
Example:
<!ELEMENT br EMPTY>
XML example:
p
<br />
Elements with Parsed Character Data
9Elements with only parsed character data are declared
with #PCDATA inside parentheses:
<!ELEMENT element-name (#PCDATA)>
( )
Example:
<!ELEMENT from (#PCDATA)>

Elements with any Contents


9Elements declared with the category
g y keyword
y ANY,, can
contain any combination of parsable data:
<!ELEMENT element-name ANY>
Example:
<!ELEMENT note ANY>
Elements with Children (sequences)
9Elements with one or more children are declared with the
name off th
the children
hild elements
l t inside
i id parentheses:
th
<!ELEMENT element-name (child1)>
or
<!ELEMENT element-name (child1,child2,...)>
Example:
p
<!ELEMENT note (to, from, heading, body)>

9When children are declared in a sequence separated by


commas, the children must appear in the same sequence in
the document

9In
In a full declaration, the children must also be declared,
and the children can also have children. The full declaration
of the "note" element is:
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
( )
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
Declaring Only One Occurrence of an Element
<!ELEMENT element-name
element name (child-name)>
(child name)>
Example:
<!ELEMENT note (message)>
( g )

9The example above declares that the child element


"message" must occur once, and only once inside the "note"
element
Declaring Minimum One Occurrence of an Element
<!ELEMENT element-name (child-name+)>
Example:
l
<!ELEMENT note (message+)>

9The + sign in the example above declares that the child


element "message"
g must occur one or more times inside the
"note" element
Declaring Zero or More Occurrences of an Element
<!ELEMENT element-name
l t ( hild
(child-name*)>
*)>
Example:
<!ELEMENT note (message
(message*)>
)>

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

9The ? sign in the example above declares that the child


element "message"
g can occur zero or one time inside the
"note" element

Declaring either/or Content


Example:
<!ELEMENT
!ELEMENT note (to, from, header, (message|body))>
(message|body))

9The example above declares that the "note" element must


contain a "to" element, a "from" element, a "header"
element, and either a "message" or a "body" element
Declaring Mixed Content
Example:
<!ELEMENT note (#PCDATA|to|from|header|message)*>

9The example
9Th l above
b declares
d l that
th t the
th "note"
" t " element
l t can
contain zero or more occurrences of parsed character data,
"to"
to , "from"
from , "header"
header , or "message"
message elements

DTD - Attributes
9In a DTD, attributes are declared with an ATTLIST
declaration

Declaring Attributes
9An attribute declaration has the followingg syntax:
y
<!ATTLIST element-name attribute-name attribute-
type default-value>
DTD example:
l
<!ATTLIST payment type CDATA "check">
XML example:
<payment type="check" >
The attribute-type can be one of the following:
Type Description
CDATA The value is character data
((en1|en2|..)
| | ) The value must be one from an enumerated list
ID The value is a unique id
IDREF The value is the id of another element
IDREFS The value is a list of other ids
NMTOKEN The value is a valid XML name
NMTOKENS The value is a list of valid XML names
ENTITY The value is an entity
ENTITIES The value is a list of entities
NOTATION The value is a name of a notation
xml: The value is a predefined xml value
The default-value can be one of the following:
Value Explanation
value
l Th default
The d f l valuel off the
h attribute
ib
#REQUIRED The attribute is required
#IMPLIED The attribute is not required
#FIXED value The attribute value is fixed

A Default Attribute Value


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

Example
DTD:
<!ATTLIST contact fax CDATA #IMPLIED>
Valid XML:
<contact fax="555-667788"
f "555 667788" //>
Valid XML:
<contact />
9Use the #IMPLIED keyword if you don't want to force
the author to include an attribute,, and yyou don't have an
option for a default value
#FIXED
Syntax
<!ATTLIST
!ATTLIST element-name
l attribute-name
ib attribute-
ib
type #FIXED "value">
Example
DTD:
<!ATTLIST sender company
p y CDATA #FIXED
"Microsoft">
Valid XML:
<sender company="Microsoft" />
Invalid XML:
<sender company=
company=“Netscape"
Netscape />
9Use the #FIXED keyword when you want an attribute to
have a fixed value without allowing the author to change it.
If an author includes another value, the XML parser will
return an error
Enumerated Attribute Values
Syntax
<!ATTLIST element-name attribute-name (en1|en2|..)
default-value>
Example
DTD:
<!ATTLIST ppayment
y type
yp ((check|cash)
| ) "cash">
XML example:
<payment type="check" />
or
<payment type="cash" />

9Use enumerated attribute values when you want the


attribute value to be one of a fixed set of legal values
DTD – Entities
9Entities are variables used to define shortcuts to standard
text or special characters

9E i references
9Entity f are references
f to entities
ii

9Entities can be declared internal or external


An Internal Entity Declaration
Syntax
<!ENTITY entity-name "entity-value">
Example
DTD Example:
<!ENTITY writer "Donald Duck.">
<!ENTITY copyright "Copyright W3Schools.">
XML example:
<author>&writer;&copyright;</author>
9Note: An entity has three parts: an ampersand (&), an
entity
y name,, and a semicolon (;)

An External Entity Declaration

Syntax
<!ENTITY entity-name SYSTEM "URI/URL">

Example
DTD Example:
<!ENTITY writer SYSTEM "wentities.dtd">
<!ENTITY copyright SYSTEM "centities.dtd">
XML example:
<author>&writer;&copyright;</author>
Introduction to XML Schema
9XML Schema is an XML-based alternative to DTD

9An XML schema describes the structure of an XML


document

9The XML Schema language is also referred to as XML


Schema Definition (XSD)

9The purpose of an XML Schema is to define the legal


building blocks of an XML document, just like a DTD

9An XML Schema:


*Defines elements that can appear in a document
*Defines attributes that can appear in a document
*Defines which elements are child elements
*Defines the order of child elements
*D fi
*Defines th
the number
b off child
hild elements
l t
*Defines whether an element is empty or can include text
*Defines
Defines data types for elements and attributes
*Defines default and fixed values for elements and
attribute
XML Schemas are the Successors of DTDs
9XML Schemas will be used in most Web applications as a
replacement
l t for
f DTDs
DTD
9Here are some reasons:
XML Schemas are extensible to future additions
XML Schemas are richer and more powerful than DTDs
XML Schemas are written in XML
XML Schemas support data types
XML Schemas support namespaces
XSD How To?
9XML documents can have a reference to a DTD or to an
XML Schema
An XML Schema
9The following example is an XML Schema file called
"note.xsd" that defines the elements of the XML document

<?xml version="1.0"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="notetype">
<
<xs:sequence>>
<xs:element name="to" type="xs:string"/>
<xs:element name="from"
name from type
type="xs:string"/>
xs:string />
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:element name="note" type="notetype"/>
</xs:schema>

9note element is a complex type because it contains other


elements.
l The
Th other
h elements
l (to,
( from,
f heading,
h di body)
b d ) are
simple types because they do not contain other elements

9Namespace: It is a way of keeping the names used by


applications
pp separate
p from each other

9Namespaces are used to group elements and attributes that


relate to each other in some special way
9As an example, modern HTML editors understand the
http://www.w3.org/1999/xhtml
p g namespace
p

9 It is unlikely that these editors ever visit the URI that


holds the XHTML namespace

9 Instead,
I t d these
th applications
li ti have
h built-in
b ilt i ffunctionality
ti lit to t
support the namespace

9The main reason a URI is used is to provide a unique


variable name to hold the namespace

9Namespace authors should use URIs that they own to


prevent conflicts
fli with
i h eachh other
h
9Namespaces are held in a unique URI (Uniform Resource
Identifier)
A Reference to an XML Schema
9This XML document has a reference to an XML Schema:

<?xml version="1.0"?>
<note
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation note.xsd
xsi:noNamespaceSchemaLocation="note.xsd">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</ t >
</note>
XSD - The <schema> Element
9The <schema> element is the root element of everyy XML
Schema
<?xml version="1.0"?>
<xs:schema>
h
...
...
</xs:schema>
9The <schema> element mayy contain some attributes

9A schema declaration often looks something like this:


<?xml version="1.0"?>
<xs:schema
xmlns:xs="http://www w3 org/2001/XMLSchema"
xmlns:xs="http://www.w3.org/2001/XMLSchema"

...
...
</xs:schema>

9The following fragment:


xmlns:xs="http://www.w3.org/2001/XMLSchema"
I di t that
Indicates th t the
th elements
l t andd data
d t types
t usedd in
i the
th
schema come from the
"http://www
http://www.w3.org/2001/XMLSchema
w3 org/2001/XMLSchema" namespace

It also specifies that the elements and data types that come
from the "http://www.w3.org/2001/XMLSchema"
namespace should be prefixed with xs:
Referencing a Schema in an XML Document

9This XML document has a reference to an XML Schema:

<?xml
? l version="1.0"?>
i "1 0"?
<note
xmlns:xsi="http://www
xmlns:xsi= http://www.w3.org/2001/XMLSchema-instance
w3 org/2001/XMLSchema instance"
xsi:noNamespaceSchemaLocation="note.xsd">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
9The following fragment:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-i
l i "htt // 3 /2001/XMLS h i
nstance"
Indicates that XML document is an instance of XML
schema, and it has come from the namespace
"http://www.w3.org/2001/XMLSchema-instance"
p g

9The following fragment:


xsi:noNamespaceSchemaLocation="note.xsd"
Used to tie the XML document with the schema definition.
The value is name of the xsd file,
file like "note
note.xsd
xsd"
XSD Simple Elements
9XML Schemas define the elements of yyour XML files

9A simple element is an XML element that contains only


text. It
I cannot contain
i any other
h elements
l or attributes
ib

Definingg a Simple
p Element
9The syntax for defining a simple element is:
<xs:element name="aaa" type="bbb"/>
Where aaa is the name of the element and bbb is the
data type of the element

9XML Schema has a lot of built-in data types

9The most common types are:


xs:string
xs:decimal
xs:integer
xs:boolean
xs:date
xs:time
Example
9Here are some XML elements:
<lastname>Refsnes</lastname>
<age>36</age>
<dateborn>1970-03-27</dateborn>

9And here are the corresponding simple element


definitions:
<xs:element
xs:element name
name="lastname"
lastname type
type="xs:string"/>
xs:string /
<xs:element name="age" type="xs:integer"/>
<xs:element name="dateborn" type="xs:date"/>
Default and Fixed Values for Simple Elements
9Simple
p elements mayy have a default value OR a fixed
value specified

9A ddefault
f l value
l isi automatically
i ll assigned
i d to the
h element
l
when no other value is specified

9In the following example the default value is "red"


<xs:element name="color" type="xs:string"
yp g default="red"/>

9A fixed value is also automatically assigned to the


element, and you cannot specify another value

9In the following example the fixed value is "red"


<xs:element name="color" type="xs:string" fixed="red"/>
XSD Attributes
9All attributes are declared as simple
p types
yp
What is an Attribute?
9Simple elements cannot have attributes. If an element has
attributes,
tt ib t it is
i considered
id d tot be
b off a complex
l type
t
How to Define an Attribute?
9The syntax
y for definingg an attribute is:
<xs:attribute name="aaa" type="bbb"/>
where aaa is the name of the attribute and bbb specifies
the data type of the attribute

9XML Schema has a lot of built-in


built in data types

9 The most common types are:


xs:string
xs:decimal
xs:integer
g
xs:boolean
xs:date
xs:time
Example
9Here is an XML element with an attribute:
<lastname lang="EN">Smith</lastname>

9And here is the corresponding attribute definition:


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

Default and Fixed Values for Attributes


9Attributes
Attributes may have a default value OR a fixed value
specified
9A default value is automatically assigned to the attribute
when no other value is specified
p

9In the following example the default value is "EN":


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

9A fixed value is also automatically assigned to the


attribute, and you cannot specify another value

9In the following example the fixed value is "EN":


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

Optional and Required Attributes


9Attributes are optional by default.
default To specify that the
attribute is required, use the "use" attribute:
<xs:attribute name="lang" type="xs:string"
use="required"/>
q
Restrictions on Content

9When an XML element


9Wh l or attribute
ib hash a data
d type
defined, it puts restrictions on the element's or attribute's
content

9If an XML element is of type


yp "xs:date" and contains a
string like "Hello World", the element will not validate

9With XML Schemas, you can also add your own


restrictions to your XML elements and attributes. These
restrictions are called facets
XSD Restrictions/Facets
9Restrictions are used to define acceptable
p values for XML
elements or attributes. Restrictions on XML elements are
called facets
R t i ti
Restrictions on Values
V l
9The following example defines an element called "age"
with a restriction.
restriction The value of age cannot be lower than 0
or greater than 120:
<xs:simpleType name="agetype">
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive
I l i value="120"/>
l "120"/
</xs:restriction>
</xs:simpleType>
<xs:element name="age" type="agetype"/>
Restrictions on a Set of Values
9To limit the content of an XML element to a set of
acceptable values, we would use the enumeration constraint
9The example below defines an element called "car" with a
restriction.
i i Th only
The l acceptable
bl values
l are: Audi,
A di Golf,
G lf
BMW:
<xs:simpleType name=
name="cartype">
cartype >
<xs:restriction base="xs:string">
<xs:enumeration value="Audi"/>
<xs:enumeration value="BMW"/>
<xs:enumeration value="Alto"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="car" type="cartype"/>
Restrictions for Datatypes
Constraint Description
enumeration Defines a list of acceptable
p values
fractionDigits Specifies the maximum number of decimal places allowed. Must be equal
to or greater than zero
length Specifies the exact number of characters or list items allowed. Must be
equal to or greater than zero
maxExclusive Specifies the upper bounds for numeric values (the value must be less than
this value)
maxInclusive
I l i S ifi the
Specifies th upper bounds
b d for
f numerici values
l (the
(th value
l mustt be
b less
l than
th
or equal to this value)
maxLength Specifies the maximum number of characters or list items allowed. Must
be equal to or greater than zero
minExclusive Specifies the lower bounds for numeric values (the value must be greater
than this value)
minInclusive
c us ve Spec
Specifies
es thee lower
owe bounds
bou ds for
o numeric
u e c values
va ues (the
( e value
va ue must
us be greater
g ea e
than or equal to this value)
minLength Specifies the minimum number of characters or list items allowed. Must
be equal to or greater than zero
pattern Defines the exact sequence of characters that are acceptable
totalDigits Specifies the exact number of digits allowed. Must be greater than zero
whiteSpace Specifies how white space (line feeds, tabs, spaces, and carriage returns) is
h dl d
XSD Complex Elements
9A complex
p element is an XML element that contains other
elements and/or attributes

9There are four


9Th f kinds
ki d off complex
l elements:
l
*Empty elements
*Elements that contain only other elements
*Elements that contain only text
*Elements that contain both other elements and text

9Note: Each of these elements may contain attributes as


well!
ll!

Examples of Complex Elements


9A complex XML element, "product", which is empty:
<product pid="1345"/>
9A complex XML element, "employee", which contains
only
l other
th elements:
l t
<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>
p y
9A complex XML element, "food", which contains only
text:
<food
f d type="dessert">Ice
"d " cream</food>
/f d
9A complex XML element, "description", which contains
both elements and text:
<description>
It happened
pp on <date lang="english">03.03.99</date>
g g
....
</description>
How to Define a Complex Element
9Look at this complex
p XML element, "employee",
p y which
contains only other elements:
<employee>
<firstname>John</firstname>
fi J h /fi
<lastname>Smith</lastname>
</employee>
9We can define a complex element in an XML Schema as:
<xs:complexType
p yp name="personinfo">
p
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:element name="employee" type="personinfo"/>
XSD Complex Empty Elements
9An empty complex element cannot have contents, only
attributes

9An empty XML element:


<product prodid
prodid="1345"
1345 />

9The "product" element above has no content at all

<xs:complexType name="prodtype">
<xs:attribute
ib name="prodid"
" did" type="xs:positiveInteger"/>
" ii I "/
</xs:complexType>
<xs:element name=
name="product"
product type=
type="prodtype"/>
prodtype />
XSD Complex Types Containing Elements Only

9An "elements-only" complex type contains an element that


contains only other elements

9An XML element, "person", that contains only other


elements:

<person>
p
<firstname>John</firstname>
<lastname>Smith</lastname>
</person>
9You can define the "person" element in a schema, like this:

<xs:complexType name="persontype">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
yp g
</xs:sequence>
</xs:complexType>
<xs:element
l name="person"
" " type="persontype"/>
" "/

9Notice the <xs:sequence> tag.


tag It means that the elements
defined ("firstname" and "lastname") must appear in that
order inside a "person"
p element
XSD Complex Text-Only Elements
9This type contains only simple content (text and
attributes),
tt ib t ) therefore
th f we add dd a simpleContent
i l C t t elementl t
around the content.
9When using simple content,
content you must define an extension
OR a restriction within the simpleContent element, like this:
<xs:complexType
p yp name="somenametype">
yp
<xs:simpleContent>
<xs:extension base="basetype">
....
....
</xs:extension>
</xs:simpleContent>
</xs:complexType>
/xs:complexType
<xs:element name="somename" type ="somenametype">
OR
<xs:complexType
p yp name="somenametype">
yp
<xs:simpleContent>
<xs:restriction base="basetype">
....
....
</
</xs:restriction>
t i ti >
</xs:simpleContent>
</xs:complexType>
<xs:element name="somename" type ="somenametype">
9Tip: Use the extension/restriction element to expand or to
limit the base simple type for the element.
9Here is an example of an XML element, "shoesize", that
contains
i text-only:l
<shoesize country="france">35</shoesize>

9The following example declares a complexType,


"shoesize". The content is defined as an integer value, and
the "shoesize" element also contains an attribute named
"country":

<xs:complexType name="shoetype">
<xs:simpleContent>
<xs:extension base="xs:integer">
<xs:attribute name="country" type="xs:string" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
/ l T
<xs:element name="shoesize" type="shoetype"/>
XSD Complex Types with Mixed Content

9An XML element,


9A l "l
"letter",
" that
h contains
i both
b h text andd
other elements:
<letter>
Dear Mr.<name>John Smith</name>.
Your order <orderid>1032</orderid>
will be shipped on <shipdate>2001-07-13</shipdate>.
</letter>
9The following schema declares the "letter" element:

<xs:complexType
< s:comple T pe name
name="lettertype"
"lettert pe" mixed="true">
mi ed "tr e">
<xs:sequence>
<xs:element name
name="name"
name type
type="xs:string"/>
xs:string />
<xs:element name="orderid" type="xs:positiveInteger"/>
<xs:element name="shipdate"
p type="xs:date"/>
yp
</xs:sequence>
</xs:complexType>
<xs:element name="letter" type="lettertype"/>

9Note: ToT enable


bl character
h t data
d t to
t appear between
b t th
the
child-elements of "letter", the mixed attribute must be set to
"true"
true

9The <xs:sequence> tag means that the elements defined


(name, orderid and shipdate) must appear in that order
inside a "letter" element
XSD Indicators
9We can control HOW elements are to be used in
documents with indicators

9There are seven indicators:


9Th i di
Order indicators:
*All
*Choice
*Sequence
q
Occurrence indicators:
*maxOccurs
*minOccurs
Group indicators:
*Group name
*attributeGroup name
Order Indicators
9Order indicators are used to define the order of the
elements
All Indicator
9The <all>
9Th < ll> indicator
i di t specifies
ifi that
th t the
th child
hild elements
l t can
appear in any order, and that each child element must occur
only once:
<xs:complexType name="persontype">
<xs:all>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:all>
/ ll
</xs:complexType>
<xs:element name=
name="person"
person type=
type="persontype"/>
persontype />
9Note: When using the <all> indicator you can set the
<minOccurs> indicator to 0 or 1 and the <maxOccurs>
indicator can only be set to 1
Choice Indicator
9The <choice>
9Th h i i di
indicator specifies
ifi thath either
i h one child
hild
element or another can occur:
<xs:complexType name=
name="persontype">
persontype >
<xs:choice>
<xs:element name="employee"
p y type="xs:string"/>
yp g
<xs:element name="member" type="xs:string"/>
</xs:choice>
</xs:complexType>
<xs:element name="person" type="persontype"/>
Sequence Indicator
9The <sequence> indicator specifies that the child elements
must appear in a specific order:
<xs:complexType name="persontype">
<xs:sequence>
xs:sequence
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<
<xs:element
l t name="person"
" " ttype="persontype"/>
" t "/>
Occurrence Indicators
9Occurrence indicators are used to define how often an
element can occur
9Note: For all "Order" and "Group" indicators (any, all,
choice, sequence, group name, and group reference) the
default value for maxOccurs and minOccurs is 1
maxOccurs Indicator
9The <maxOccurs> indicator specifies the maximum
number of times an element can occur:
<xs:complexType
xs:complexType name
name="persontype">
persontype
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string"
maxOccurs="10"/>
</
</xs:sequence>
>
</xs:complexType>
<xs:element name
name="person"
person type
type="persontype"/>
persontype />
9The example above indicates that the "child_name"
element can occur a minimum of one time ((the default value
for minOccurs is 1) and a maximum of ten times in the
"person" element
minOccurs Indicator
9The <minOccurs> indicator specifies the minimum
number of times an element can occur

9
9Tip: T allow
To ll an element
l to appear an unlimited
li i d number
b
of times, use the maxOccurs="unbounded" statement
Group Indicators
9Group indicators are used to define related sets of
elements
Presenting XML Using XML Processors:
DOM andd SAX
XML Parsers
9 The parser is the engine for interpreting our XML
documents
9 The parser reads the XML and prepares the information
for your application
How to use a parser
1. Create a parser object
2. Pass your XML document to the parser
3 Process the results
3.
Types of Parsers
DOM - Document Object Model
SAX - Simple API for XML
91
XML DOM Introduction
9The XML DOM defines a standard way for accessing and
manipulating
i l ti XML
What is the DOM?
9The
The DOM is a W3C (World Wide Web Consortium)
standard
9The DOM defines a standard for accessing documents like
XML and HTML:
"The W3C Document Object Model (DOM) is a platform
andd language-neutral
l t l interface
i t f th t allows
that ll programs andd
scripts to dynamically access and update the content,
structure and style of a document.
structure, document "
9The DOM is separated into 3 different parts:
9Core DOM - standard model for anyy structured document
9XML DOM - standard model for XML documents
9HTML DOM - standard model for HTML documents
9The DOM defines the objects and properties of all
document elements, and the methods (interface) to access
them

Wh is
What i the
h HTML DOM?
9The HTML DOM defines the objects and properties of
all HTML elements,
elements and the methods (interface) to access
them

What is the XML DOM?


The XML DOM is:
9A standard object model for XML
9A standard programming interface for XML
9The XML DOM defines the objects
j and p
properties
p of all
XML elements, and the methods (interface) to access them
XML DOM Nodes
9According to the DOM, everything in an XML document
is a node
The DOM says:
9The entire document is a document node
9Every XML element is an element node
9The text in the XML elements are text nodes
9E
9Every attribute
ib is i an attribute
ib node
d
9Comments are comment nodes
DOM Example (books
(books.xml)
xml)
<?xml version="1.0" ?>
<bookstore>
<b k category="cooking">
<book t " ki ">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title
title lang
lang="en">XQuery
en XQuery Kick Start</title>
Start /title
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
y y
<price>39.95</price>
</book>
</bookstore>

9The root node in the XML above is named <bookstore>


9All other nodes in the document are contained within
<bookstore>
9Th root node
9The d <bookstore>
b k h ld four
holds f <book>
b k nodes d
9The first <book> node holds four nodes: <title>, <author>,
<year> and <price>,
<year>, <price> which contains one text node each,
each
"Everyday Italian", "Giada De Laurentiis", "2005", and
"30.00"
Text is Always Stored in Text Nodes
9A common error in DOM pprocessing g is to expect
p an
element node to contain text
9However, the text of an element node is stored in a text
node
d
9In this example: <year>2005</year>, the element node
<year> holds a text node with the value "2005"
<year>, 2005
"2005" is not the value of the <year> element!

XML DOM Node Tree


9The XML DOM views an XML document as a tree-
str ct re The tree structure
structure. str ct re is called a node-tree
node tree
9All nodes can be accessed through the tree. Their contents
can be modified or deleted, and new elements can be created
Example
Node Parents, Children, and Siblings

9The terms parent, child, and sibling are used to describe


the relationships. Parent nodes have children. Children on
the
h same level
l l are called
ll d siblings
ibli (b h or sisters)
(brothers i )

9In a node tree,


tree the top node is called the root

9Everyy node,, except


p the root,, has exactly
y one pparent node

9A node can have any number of children

9Siblings are nodes with the same parent


First Child - Last Child

Lookk at the
L h following
f ll i XML fragment:
f
<bookstore>
<book category="cooking">
category= cooking >
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
9In the XML above,
above the <title> element is the first child of
the <book> element, and the <price> element is the last
child of the <book>
book element
9Furthermore, the <book> element is the parent node of the
<title>,, <author>,, <year>,
y , and <price>
p elements

XML DOM Parsing

9The XML DOM contains methods (functions) to traverse


XML trees,
trees access,
access insert,
insert and delete nodes

9However, before an XML document can be accessed and


manipulated, it must be loaded into an XML DOM object

9The parser reads


9Th d XML into
i memory andd converts it
i into
i an
XML DOM object that can be accessed with JavaScript
Load an XML Document (loadxmldoc.js file)
function loadXMLDoc(dname)
{
var xmlDoc;
try { xmlDoc=new ActiveXObject("Microsoft.XMLDOM");}
catch(e)
{
try{xmlDoc=document.implementation.createDocument("","",null);}
catch(e) { alert(e.message);}
}
tryy
{
xmlDoc.async="false";
xmlDoc load(dname);
xmlDoc.load(dname);
return(xmlDoc);
}
catch(e) {alert(e.message);}
return(null);
}
9The following example uses the loadXMLDoc() function to load books.xml:
<html> (bookshtml.html file)
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head>
<body>
body
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeVal
( g y g ( )[ ] [ ]
ue + "<br />");
document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeV
alue + "<br />");
document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeVal
ue);
</script>
</b d >
</body>
</html>
Output:
Everyday Italian
Giada De Laurentiis
2005
Load an XML String (loadxmlstring.js file)
function loadXMLString(txt)
{
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
lD "f l "
xmlDoc.loadXML(txt);
return xmlDoc;
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,
p p g( "text/xml");
)
return xmlDoc;
}
catch(e) {alert(e.message)}
}
return null;
}
bkhtml.html file
<html>
<head>
<script type=
type="text/javascript"
text/javascript src=
src="loadxmlstring
loadxmlstring.js
js"></script>
></script>
</head>
<body> Output:
<script
script type
type="text/javascript">
text/javascript
text="<bookstore>" E
Everyday
d Italian
I li
text=text+"<book>"; Giada De Laurentiis
text=text+"<title>Everyday Italian</title>"; 2005
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
text=text+"</bookstore>";
xmlDoc=loadXMLString(text);
document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeVal
ue);
)
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].node
Value);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeVa
lue); </script> </body> </html>
XML DOM - Properties and Methods

9The DOM models XML as a set of node objects. The


nodes can be accessed with JavaScript or other
programming
i languages
l

XML DOM Properties


p

These are some typical DOM properties:


9x.nodeName - the name of x
9x.nodeValue - the value of x
9x parentNode - the parent node of x
9x.parentNode
9x.childNodes - the child nodes of x
9x.attributes
x.attributes - the attributes nodes of x

Note: In the list above, x is a node object


XML DOM Methods

9x.getElementsByTagName(name) - get all elements with a


specified tag name
9
9x.appendChild(node)
dChild( d ) - insert
i a child
hild node
d to x
9x.removeChild(node) - remove a child node from x

Note: In the list above, x is a node object


Example
9The JavaScript code to get the text from the first <title>
element in books.xml:
txt=xmlDoc.getElementsByTagName("title")[0].childNodes
lD El B T N (" i l ")[0] hildN d
[0].nodeValue
9After the execution of the statement,
statement txt will hold the
value "Everyday Italian"
XML DOM - Accessing Nodes

You can access a node in three ways:


1. By using the getElementsByTagName() method
2 By
2. B looping
l i through
h h (traversing)
( i ) the
h nodes
d tree
3. By navigating the node tree, using the node relationships

The getElementsByTagName() Method


getElementsByTagName() returns all elements with a
specified tag name
Syntax
node getElementsByTagName("tagname");
node.getElementsByTagName( tagname );
Example
9The following example returns all <title> elements under
the x element:
x.getElementsByTagName("title");
9Note that the example above only returns <title> elements
under the x node

9 To return all <title> elements in the XML document use:


xmlDoc.getElementsByTagName("title");
where xmlDoc is the document itself (document node)

DOM Node List


9The getElementsByTagName() method returns a node
list.A node list is an array of nodes.

9The following
9Th f ll i code d loads
l d "books.xml"
"b k l" into
i xmlDoc
lD usingi
loadXMLDoc() and stores a list of <title> nodes (a node list)
in the variable x:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title");
g y g ( );

9The <title> elements in x can be accessed by index


number. To access the third <title> you can write:: y=x[2];

N t The
Note: Th index
i d starts
t t att 0
DOM Node List Length
9The length
g pproperty
p y defines the length
g of a node list ((the
number of nodes)

9You can loop through a node list by using the length


property:
Example
<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head> Output:
<body>
<script type=
type="text/javascript">
text/javascript > EverydayItalian
y y
xmlDoc=loadXMLDoc("books.xml"); Harry Potter
x=xmlDoc.getElementsByTagName("title"); XQuery Kick Start
for (i=0;i<x.length;i++)
(i 0;i x.length;i ) Learning XML
{
document.write(x[i].childNodes[0].nodeValue);
document.write("<br />");
}
</script>
</body>
</html>
Node Types

9The documentElement property of the XML document is


the root node
9The nodeName property of a node is the name of the node
9The nodeType property of a node is the type of the node
Example
<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>
</head> Output:
<body>
body bookstore
<script type="text/javascript">
xmlDoc=loadXMLDoc("books.xml");
1
document.write(xmlDoc.documentElement.nodeName);
document.write("<br />");
document.write(xmlDoc.documentElement.nodeType);
</script>
</body>
</html>

Navigating Node Relationships


9The following image illustrates a node tree and the
relationship between the nodes:
Example
<html>
<head>
<script type="text/javascript" src="loadxmldoc.js"></script>

</head>
<body>
b d
<script type="text/javascript"> Output:
xmlDoc=loadXMLDoc("books.xml");
var k=xmlDoc
k=xmlDoc.getElementsByTagName(
getElementsByTagName("book")[0];
book )[0]; bookstore
document.write(k.parentNode.nodeName+"<br/>"); title
x=xmlDoc.getElementsByTagName("book")[0].childNodes; author
yy=xmlDoc
xmlDoc.getElementsByTagName(
getElementsByTagName("book")[0]
book )[0].firstChild;
firstChild; year
for (i=0;i<x.length;i++) price
{
if (y
(y.nodeType==1)
yp )
{//Process only element nodes (type 1)
document.write(y.nodeName + "<br />");
}
y=y.nextSibling;
}
</script> </body> </html>
XML DOM Node Information
9The nodeName, nodeValue, and nodeType
yp pproperties
p
contain information about nodes

Node Properties
9Three important node properties are:
*nodeName
*nodeValue
*nodeType

The nodeName Property


9The
The nodeName property specifies the name of a node

Example
Refer slide -112
document.write(xmlDoc.documentElement.nodeName);
The nodeValue Property
9The nodeValue p
property
p y specifies
p the value of a node

Get the Value of an Element

Example
Refer slide -105
document write(xmlDoc getElementsByTagName("title")[0]
document.write(xmlDoc.getElementsByTagName( title )[0].childNod
childNod
es[0].nodeValue);

Change the Value of an Element

Example
p
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x nodeValue="Easy
x.nodeValue= Easy Cooking
Cooking";;
Result:"Everyday Italian" is replaced with "Easy Cooking"
The nodeType Property
9The nodeType
yp pproperty
p y specifies
p the type
yp of node

The most important node types are:


Node type NodeType
Element 1
A ib
Attribute 2
Text 3
Comment 8
Document 9
Example
Refer slide -112
document.write(xmlDoc.documentElement.nodeType);
DOM Attribute List (Named Node Map)

9The attributes property of an element node returns a list of


attribute nodes

9This is called a named node map, and is similar to a node


list except for some differences in methods and properties
list,

9A attribute list keepsp itself up-to-date.


p If an attribute is
deleted or added, the list is automatically updated

9The following code fragment displays the value of the


"category" attribute, and the number of attributes, of a book:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0].attributes;
g y g ( )[ ] ;
document.write(x.getNamedItem("category").nodeValue);
document.write("<br />" + x.length);
Output:
cooking
1

9After
After the execution of the code above,
above x.length
x length = is the
number of attributes and x.getNamedItem() can be used to
return an attribute node

Get the Value of an Attribute


9In the DOM,
DOM attributes are nodes.
nodes Attribute nodes have
text values
9The way to get the value of an attribute, is to get its text
value. This can be done usingg the ggetAttribute()
() method or
using the nodeValue property of the attribute node

9The following code retrieves the text value of the "lang"


attribute of the first <title> element:
xmlDoc=loadXMLDoc("books.xml");
lD l dXMLD ("b k l")
txt=xmlDoc.getElementsByTagName("title")[0].getAttribute
( lang );
("lang");
Result: txt = "en"
SAX (Simple API for XML)
9SAX provides a mechanism for reading data from an
XML document.
d t It is
i a popular
l alternative
lt ti tot the
th Document
D t
Object Model (DOM)
Differences between DOM and SAX
DOM SAX
DOM is a tree based p parsing
g method SAX is an event based p
parsing
g method
used to parse the given XML document used to parse the given XML document
The entire XML document is stored in The parsing is done by generating the
the memory before actual processing sequence of events or it calls handler
.Hence it requires more memory functions
It is useful for smaller applications It is useful for larger applications
W can insert
We i or delete
d l a node
d W can insert
We i or delete
d l a node
d

Traversing is done in any direction Top to bottom traversing is done

Generally used at client -side Generally used at sever-side


Displaying XML with CSS
9With CSS ((Cascadingg Style
y Sheets)) y
you can add display
p y
information to an XML document
Example
(bookscss css)
(bookscss.css)
bookstore{background-color: #00FF00;width: 100%;}
book{display: block;margin-bottom: 30pt;margin-left: 0;}
title{color: #FF0000;font-size: 20pt;}
author{color: #0000FF;font-size: 20pt;}
yyear,price{color:
,p { #000000;margin-left:
; g 20pt;}
p ;}
(books.xml)
<?xml version="1.0"?>
<?xml stylesheet type=
<?xml-stylesheet type="text/css"
text/css href=
href="bookscss
bookscss.css
css"?>
?>
<bookstore>
<book category="COOKING">
<title lang="en">EverydayItalian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<titlee lang="en">Harry
g e y Potter</title>
o e / e
<author>J K.Rowling</author>
<year>2005</year>
<price>29 99</price>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
y y
<price>39.95</price>
</book>
</bookstore>
Output:
Displaying XML with XSLT

9With XSLT you can transform an XML document into


HTML

9XSLT is the recommended style sheet language of XML

9XSLT (eXtensible Stylesheet Language Transformations)


is far more sophisticated
p than CSS

9One way to use XSLT is to transform XML into HTML


before it is displayed by the browser
Example
(cdxsl.xsl)
<?xml version=
version="11.0
0"?>
?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template
xsl:template match
match="/">
/
<html>
<body>
<h2>My CD Collection</h2>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="cd">
<p>
< l
<xsl:apply-templates
l t l t select="title"/>
l t "titl "/>
<xsl:apply-templates select="artist"/>
</p>
</xsl:template>
<xsl:template match="title">
Title: <span style="color:#ff0000“>
<xsl:value-of select="."/></span>
<br />
</xsl:template>
<xsl:template match="artist">
Artist: <span style="color:#00ff00">
<xsl:value-of
xsl:value of select
select="."/></span>
. / /span
<br />
</xsl:template>
</xsl:stylesheet>
(cdxml.xml)
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="cdxsl.xsl"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
< ti t>B b Dylan</artist>
<artist>Bob D l </ ti t>
<country>USA</country>
<company>Columbia</company>
<price>10 90</price>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
y
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<
<year>1988</year>
>1988</ >
</cd>
<cd>
<title>Greatest Hits</title>
<artist>Dolly Parton</artist>
<country>USA</country>
<company>RCA</company>
<price>9 90</price>
<price>9.90</price>
<year>1982</year>
</cd>
</catalog>
Output:

You might also like