0% found this document useful (0 votes)
48 views61 pages

Chapter 1 XML Basic3

Uploaded by

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

Chapter 1 XML Basic3

Uploaded by

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

Chapter 1

Extensible Markup Language


XML

1
Outline
• Introduction
• XML tree
• XML syntax rules
• XML entity references
• XML elements
• XML attributes
• XML namespaces

2
What is XML?
• XML stands for EXtensible Markup Language
• XML is a markup language much like HTML
• XML was designed to describe data, not to display
data
• XML tags are not predefined. You must define your
own tags
• XML is designed to be self-descriptive
• XML is a W3C Recommendation

3
The Difference between XML and HTML

• XML is not a replacement for HTML.


• XML and HTML were designed with different
goals:
– XML was designed to describe data, with focus on
what data is
– HTML was designed to display data, with focus on
how data looks
– HTML is about displaying information, while XML
is about carrying information.
4
A. With XML You Invent Your Own Tags
• These tags are "invented" by the author of the
XML document.
• That is because the XML language has no
predefined tags.
• The tags used in HTML are predefined.
• HTML documents can only use tags defined in the
HTML standard (like <p>, <h1>, etc.).
• XML allows the author to define his/her own tags
and his/her own document structure.
5
B.XML is Not a Replacement for HTML
• XML is a complement to HTML.
• In most web applications, XML is used to describe
data, while HTML is used to format and display the
data.
• Best description of XML is this:
• XML is a software- and hardware-independent tool
for carrying information.
• XML is a W3C Recommendation
• XML became a W3C Recommendation on February
10, 1998.
6
How Can XML be used?

• XML is used in many aspects of web development, often to


simplify data storage and sharing.
• XML Separates Data from HTML
• If you need to display dynamic data in your HTML
document, it will take a lot of work to edit the HTML each
time the data changes.
• With XML, data can be stored in separate XML files. This
way you can concentrate on using HTML/CSS for display
and layout, and be sure that changes in the underlying data
will not require any changes to the HTML.
• With a few lines of JavaScript code, you can read an
external XML file and update the data content of your web
page. 7
XML Simplifies Data Sharing
• In the real world, computer systems and databases contain
data in incompatible formats.
• XML 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 can be shared by
different applications.

XML Simplifies Data Transport


• One of the most time-consuming challenges for developers is
to exchange data between incompatible systems over the
Internet.
• Exchanging data as XML greatly reduces this complexity, since
the data can be read by different incompatible applications.
8
• XML Simplifies Platform Changes
• Upgrading to new systems (hardware or
software platforms), is always time
consuming. Large amounts of data must be
converted and incompatible data is often lost.

• XML data is stored in text format. This makes


it easier to expand or upgrade to new
operating systems, new applications, or new
browsers, without losing data.

9
XML Makes Your Data More Available
• Different applications can access your data, not only in HTML
pages, but also from XML data sources.
• With XML, your data can be available to all kinds of "reading
machines" (Handheld computers, voice machines, news feeds,
etc.), and make it more available for blind people, or people with
other disabilities.

Internet Languages Written in XML


• Several Internet languages are written in XML. Here are some
examples:
• XHTML 
• XML Schema
• SVG
• WSDL
• RSS 10
XML Tree
• XML documents form a tree structure that starts at
"the root" and branches to "the leaves".
• XML documents use a self-describing and simple
syntax:
<? Xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>
• The first line is the XML declaration. It defines the XML
version (1.0). 11
Cont’
• The next line describes the root element of the document
(like saying: "this document is a note"):
<note>
• The next 4 lines describe 4 child elements of the root (to,
from, heading, and body):
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
• And finally the last line defines the end of the root element:
</note>
• You can assume, from this example, that the XML document
contains a note to Tove from Jani.
• Don't you agree that XML is pretty self-descriptive? 12
XML Documents Form a Tree Structure

• XML documents must contain a root element. This


element is "the parent" of all other elements.
• The elements in an XML document form a document
tree.
• The tree starts at the root and branches to the lowest
level of the tree.
• All elements can have sub elements (child elements):
<root>
  <child>
    <subchild>.....</subchild>
  </child>
</root> 13
Cont’
• The terms parent, child, and sibling are used
to describe the relationships between
elements. Parent elements have children.
Children on the same level are called siblings
(brothers or sisters).

14
Exercise: Write the xml code for the following tree

15
Solution
<bookstore>
  <book category="COOKING">
    <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. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="WEB">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>
16
Cont’
• The root element in the example is
<bookstore>. All <book> elements in the
document are contained within <bookstore>.
• The <book> element has 4 children: <title>, <
author>, <year>, <price>.

17
XML Syntax Rules

1. All XML Elements Must Have a Closing Tag


•In HTML, some elements do not have to
have a closing tag:
•<p>This is a paragraph.
<br>
•In XML, it is illegal to omit the closing
tag. All elements must have a closing
tag:
•<p>This is a paragraph.</p>
<br />
18
Con’t
• Note: You might have noticed from the
previous example that the XML declaration did
not have a closing tag. This is not an error. The
declaration is not a part of the XML document
itself, and it has no closing tag.

19
2.XML Tags are Case Sensitive

•XML tags are case sensitive. The tag


<Letter> is different from the tag <letter>.
•Opening and closing tags must be written
with the same case:
•<Message>This is incorrect</message>
<message>This is correct</message>
•Note: "Opening and closing tags" are often
referred to as "Start and end tags". Use
whatever you prefer. It is exactly the same
thing.

20
3.XML Elements Must be Properly Nested
•In HTML, you might see improperly nested
elements:
<b><i>This text is bold and
italic</b></i>
In XML, all elements must be properly
nested within each other:
<b><i>This text is bold and
italic</i></b>
In the example above, "Properly nested"
simply means that since the <i> element is
opened inside the <b> element, it must be
closed inside the <b> element. 21
4.XML Documents Must Have a Root Element

•XML documents must contain one element that is


the parent of all other elements. This element is
called the rootelement.
•<root>
  <child>
    <subchild>.....</subchild>
  </child>
</root>

22
5.XML Attribute Values Must be quoted
• XML elements can have attributes in name/value pairs just
like in HTML.
• In XML, the attribute values must always be quoted.
• Study the two XML documents below. The first one is
incorrect, the second is correct:
<note date=12/11/2007>
  <to>Tove</to>
  <from>Jani</from>
</note>
 
<note date="12/11/2007">
  <to>Tove</to>
  <from>Jani</from>
</note>
The error in the first document is that the date attribute in the
note element is not quoted.

23
Entity References
• Some characters have a special meaning
in XML.
• If you place a character like "<" inside an
XML element, it will generate an error
because the parser interprets it as the
start of a new element.
• This will generate an XML error:
<message>if salary < 1000 then</message>
• To avoid this error, replace the "<" character with
an entity reference:
<message>if salary &lt; 1000 then</message> 24
There are 5 predefined entity references in XML:

&lt; < less than

&gt; > greater than

&amp; & ampersand 

&apos; ' apostrophe

&quot; " quotation mark

Note: Only the characters "<" and "&" are strictly illegal in XML. The greater than
character is legal, but it is a good habit to replace it.
25
Comments in XML
The syntax for writing comments in XML is similar
to that of HTML.
<!-- This is a comment -->
White-space is preserved in XML
HTML truncates multiple white-space characters to
one single white-space:
With XML, the white-space in a document is not truncated.

HTML: Hello           Tove


Output: Hello Tove

26
XML Elements
• What is an XML Element?
• An XML element is everything from
(including) the element's start tag to
(including) the element's end tag.
• An element can contain:
– other elements
– text
– attributes
– or a mix of all of the above...

27
Example
<bookstore>
  <book category="CHILDREN">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="WEB">
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
28
</bookstore>
Cont’
• In the example above, <bookstore> and
<book> have element contents,
because they contain other elements.
<book> also has
an attribute (category="CHILDREN").
<title>, <author>, <year>, and <price>
have text content because they contain
text.

29
Empty XML Elements
• An alternative syntax can be used for XML
elements with no content:
• Instead of writing a book element (with no
content) like this:
<book></book>
• It can be written like this:
<book />
• This sort of element syntax is called self-closing.

30
XML Naming Rules
• XML elements must follow these naming rules:
– Names can contain letters, numbers, and other characters
– Element names must start with a letter or underscore
– Names cannot start with a number or punctuation
character
– Names cannot start with the letters xml (or XML, or Xml,
etc)
– Names cannot contain spaces
– Element names can contain letters, digits, hyphens,
underscores, and periods
Any name can be used, no words are reserved. (except xml).
31
Best Naming Practices
• Make names descriptive: <first_name>, <last_name>.
• Make names short and simple, like this: <book_title> not like
this: <the_title_of_the_book>.
• Avoid "-". If you name something "first-name", some
software may think you want to subtract name from first.
• Avoid ".". If you name something "first.name", some
software may think that "name" is a property of the object
"first."
• Avoid ":". Colons are reserved to be used for something
called namespaces (more later).
• Non-English letters like éòá are perfectly legal in XML, but
watch out for problems if your software doesn't support
them. 32
Common Naming Styles

Style Example Description


Lower case <firstname> All letters lower case

Upper case <FIRSTNAME> All letters upper case

Underscore <first_name> Underscore separates


words
Pascal case <FirstName> Uppercase first letter in
each word

Camel case <firstName> Uppercase first letter in


each word except the
first
33
XML Elements are Extensible
• XML elements can be extended to carry more
information.
• Look at the following XML example:
• <note>
  <to>Tove</to>
  <from>Jani</from>
  <body>Don't forget me this weekend!</body>
</note>
• Let's imagine that we created an application that
extracted the <to>, <from>, and <body> elements
from the XML document to produce this output: 34
MESSAGE
To: Tove
From: Jani
Don't forget me this weekend!

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>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

Should 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 produce the
same output.
One of the beauties of XML, is that it can be extended without
breaking applications. 35
XML Attributes
• In HTML, attributes provide additional
information about elements:
• <img src="computer.gif">
<a href="demo.asp">
• Attributes often provide information that is not
a part of the data.
• In the example below, the file type is irrelevant
to the data, but can be important to the
software that wants to manipulate the element:
• <file type="gif">computer.gif</file>
36
XML Attributes Must be Quoted
• Attribute values must always be quoted. Either single or
double quotes can be used. For a person's sex, the person
element can be written like this:
• <person sex="female">
or like this:
• <person sex='female'>
• If the attribute value itself contains double quotes you can
use single quotes, like in this example:
• <gangster name='George "Shotgun" Ziegler'>
• or you can use character entities:
• <gangster name="George &quot;Shotgun&quot; Ziegler">
37
XML Elements vs. Attributes
• Take a look at these examples:
• <person sex="female">
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>
• <Person>
  <sex>female</sex>
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>
• In the first example sex is an attribute. In the last, sex is an
element. Both examples provide the same information.
• There are no rules about when to use attributes or when to
use elements. Attributes are handy in HTML. In XML
advisable is to avoid them. Use elements instead. 38
W3school’s Favorite Way
The following three XML documents contain exactly the same
information:
•A date attribute is used in the first example:
•<note date="10/01/2008">
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>
•A date element is used in the second example:
•<note>
  <date>10/01/2008</date>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>
39
An expanded date element is used in the
third: (THIS w3s FAVORITE):
<note>
  <date>
    <day>10</day>
    <month>01</month>
    <year>2008</year>
  </date>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

40
Avoid XML Attributes?
• Some of the problems with using attributes are:
– attributes cannot contain multiple values (elements can)
– attributes cannot contain tree structures (elements can)
– attributes are not easily expandable (for future changes)
• Attributes are difficult to read and maintain. Use
elements for data. Use attributes for information
that is not relevant to the data.
• Don't end up like this:
• <note day="10" month="01" year="2008"
to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note> 41
XML Attributes for Metadata
Sometimes ID references are assigned to elements. These IDs
can be used to identify XML elements in much the same way as
the id attribute in HTML. This example demonstrates this:
<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: Reminder</heading>
    <body>I will not</body>
  </note>
</messages> 42
Cont’
• The id attributes above are for identifying the
different notes. It is not a part of the note
itself.
• metadata (data about data) should be stored
as attributes, and the data itself should be
stored as elements.

43
XML Namespaces

•XML Namespaces provide a method to avoid element name conflicts.

Name Conflicts
•In XML, element names are defined by the developer. This often results in a
conflict when trying to mix XML documents from different XML applications.
•This XML carries HTML table information:
<table>
  <tr>
    <td>Apples</td>
    <td>Bananas</td>
  </tr>
</table>
•This XML carries information about a table (a piece of furniture):
<table>
  <name>African Coffee Table</name>
  <width>80</width>
  <length>120</length>
</table>

44
Cont’
• If these XML fragments were added together,
there would be a name conflict. Both contain
a <table> element, but the elements have
different content and meaning.

• A user or an XML application will not know


how to handle these differences.

45
Solving the Name Conflict Using a Prefix
•Name conflicts in XML can easily be avoided using a name prefix.
•This XML carries information about an HTML table, and a piece of furniture:
<h:table>
  <h:tr>
    <h:td>Apples</h:td>
    <h:td>Bananas</h:td>
  </h:tr>
</h:table>

<f:table>
  <f:name>African Coffee Table</f:name>
  <f:width>80</f:width>
  <f:length>120</f:length>
</f:table>
•In the example above, there will be no conflict because the two <table>
elements have different names.

46
XML Namespaces - The xmlns Attribute
• When using prefixes in XML, a so-called namespace for the
prefix must be defined.
• The namespace is defined by the xmlns attribute in the start
tag of an element.

47
•The namespace declaration has the following syntax. xmlns:
prefix="URI".
<root>

<h:table xmlns:h="http://www.w3.org/TR/html4/">
  <h:tr>
    <h:td>Apples</h:td>
    <h:td>Bananas</h:td>
  </h:tr>
</h:table>

<f:table xmlns:f="http://www.w3schools.com/furniture">
  <f:name>African Coffee Table</f:name>
  <f:width>80</f:width>
  <f:length>120</f:length>
</f:table>
</root>

48
Cont’
• In the example above, the xmlns attribute in
the <table> tag give the h: and f: prefixes a
qualified namespace.
• When a namespace is defined for an element,
all child elements with the same prefix are
associated with the same namespace.

50
•Namespaces can be declared in the elements where they are
used or in the XML root element:
<root xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">

<h:table>
  <h:tr>
    <h:td>Apples</h:td>
    <h:td>Bananas</h:td>
  </h:tr>
</h:table>

<f:table>
  <f:name>African Coffee Table</f:name>
  <f:width>80</f:width>
  <f:length>120</f:length>
</f:table>
</root>
51
• Note: The namespace URI is not used by the parser to look
up information.
• The purpose is to give the namespace a unique name.
However, often companies use the namespace as a pointer
to a web page containing namespace information.

Uniform Resource Identifier (URI)


• A Uniform Resource Identifier (URI) is a string of characters
which identifies an Internet Resource.
• The most common URI is the Uniform Resource
Locator (URL) which identifies an Internet domain address.
Another, not so common type of URI is the Universal
Resource Name (URN).
• In our examples we will only use URLs.
52
Default Namespaces
•Defining a default namespace for an element saves us from using
prefixes in all the child elements. It has the following syntax:
•xmlns="namespaceURI"
•This XML carries HTML table information:
<table xmlns="http://www.w3.org/TR/html4/">
  <tr>
    <td>Apples</td>
    <td>Bananas</td>
  </tr>
</table>
•This XML carries information about a piece of furniture:
<table xmlns="http://www.w3schools.com/furniture">
  <name>African Coffee Table</name>
  <width>80</width>
  <length>120</length>
</table>
53
Namespaces in Real Use
• XSLT is an XML language that can be used to
transform XML documents into other formats,
like HTML.
• In the XSLT document below, you can see that
most of the tags are HTML tags.
• The tags that are not HTML tags have the prefix
xsl, identified by the namespace
xmlns:xsl="http://www.w3.org/1999/XSL/Transf
orm":

54
<?xml version="1.0" encoding="UTF-8"?>

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

<xsl:template match="/">
<html>
<body>
  <h2>My CD Collection</h2>
  <table border="1">
    <tr>
      <th style="text-align:left">Title</th>
      <th style="text-align:left">Artist</th>
    </tr>
    <xsl:for-each select="catalog/cd">
    <tr>
      <td><xsl:value-of select="title"/></td>
      <td><xsl:value-of select="artist"/></td>
    </tr>
    </xsl:for-each>
  </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
55
XML Encoding

• XML documents can contain international characters, like Norwegian æøå,


or French êèé.
• To avoid errors, you should specify the encoding used, or save your XML files
as UTF-8.
Character Encoding
• Character encoding defines a unique binary code for each different
character used in a document. In computer terms, character encoding are
also called character set, character map, code set, and code page.
Unicode
• Unicode is an industry standard for character encoding of text documents. It
defines (nearly) every possible international character by a name and a
number.
• Unicode has two variants: UTF-8 and UTF-16.
• UTF = Universal character set Transformation Format.
• UTF-8 uses 1 byte (8-bits) to represent characters in the ASCII set, and two
or three bytes for the rest.
• UTF-16 uses 2 bytes (16 bits) for most characters, and four bytes for the rest.
56
XML Encoding
• The first line in an XML document is called the prolog:
• <?xml version="1.0"?>
• The prolog is optional. Normally it contains the XML version
number.
• It can also contain information about the encoding used in the
document. This prolog specifies UTF-8 encoding:
• <?xml version="1.0" encoding="UTF-8"?>
• The XML standard states that all XML software must
understand both UTF-8 and UTF-16.
• UTF-8 is the default for documents without encoding
information.
• In addition, most XML software systems understand
encodings like ISO-8859-1, Windows-1252, and ASCII.
57
XML Errors

• Most often, XML documents are created on one


computer, uploaded to a server on a second
computer, and displayed by a browser on a third
computer.
• If the encoding is not correctly interpreted by all the
three computers, the browser might display
meaningless text, or you might get an error message.

• For high quality XML documents, UTF-8 encoding is


the best to use. UTF-8 covers international
characters, and it is also the default, if no encoding is
declared.
58
Conclusion
• When you write an XML document:
• Use an XML editor that supports encoding
• Make sure you know what encoding the editor
uses
• Describe the encoding in the encoding attribute
• UTF-8 is the safest encoding to use
• UTF-8 is the web standard

59
Viewing XML Files

• Raw XML files can be viewed in all major


browsers.
• Don't expect XML files to be displayed as
HTML pages.

60
XML editor tools
I recommend:
• EditiX
• Altova xmlspy

61
QUIZ
1. Select which of the following XML documents
are well-formed XML documents.
a . <productname>Electric Water
Heater&piccoro_</productname>
b . <productname>”Water
Purifier(<<6>>)”</productname>
c . <productname>Dehumidifier "XZ001"
</productname>
d . <productname/ >
62

You might also like