You are on page 1of 106

I H C N NG TRUNG TM PHT TRI N PH N M M

XML Tutorial

I/ What is XML?
XML is a markup language for documents containing structured information. Structured information contains both content :
. words, pictures, etc. . some indication of what role that content plays. For example : content in a section heading has a different meaning from content in a footnote, which means something different than content in a figure caption or content in a database table, etc.

A markup language is a mechanism to identify structures in a document. The XML specification defines a standard way to add markup to documents.

An example XML document


A simple XML document :
<?xml version="1.0"?> <Root> <Person> <FirstName>Janet</FirstName> <Middle>Q</Middle> <LastName>Leverling</LastName> <Address> <Address1>123 Elm</Address1> <Address2>bis</Address2> <City>Pleasantville</City> <State>MA</State> <Zip>12345</Zip> </Address> </Person> </Root>

So XML is Just Like HTML?


No. In HTML, both the tag semantics and the tag set are fixed.
Ex : An <h1> is always a first level heading and the tag <ati.product.code> is meaningless.

XML specifies neither semantics nor a tag set.


In fact XML is really a meta-language for describing markup languages. In other words, XML provides a facility to define tags and the structural relationships between them. Since there's no predefined tag set, there can't be any preconceived semantics.

All of the semantics of an XML document will either be defined by the applications that process them or by stylesheets.

So XML is Just Like SGML?


No. XML is defined as an application profile of SGML. SGML is the Standard Generalized Markup Language defined by ISO 8879. SGML is not well suited to serving documents over the web Defining XML as an application profile of SGML means that any fully conformant SGML system will be able to read XML documents. Using and understanding XML documents does not require a system that is capable of understanding the full generality of SGML.

Why XML?
XML was created so that richly structured documents could be used over the web. HTML, as we've already discussed, comes bound with a set of semantics and does not provide arbitrary structure. SGML provides arbitrary structure, but is too difficult to implement just for a web browser. In many organizations, filtering SGML to XML will be the standard procedure for web delivery.

XML development goals?


1. It shall be straightforward to use XML over the Internet. Users must be able to view XML documents as quickly and easily as HTML documents. 2. XML shall support a wide variety of applications.
Ex : authoring, browsing, content analysis, etc.

3. XML shall be compatible with SGML. 4. It shall be easy to write programs that process XML documents. 5. The number of optional features in XML is to be kept to an absolute minimum, ideally zero.

XML development goals?


6. XML documents should be human-legible and reasonably clear. 7. The XML design should be prepared quickly. 8. The design of XML shall be formal and concise. 9. XML documents shall be easy to create. 10. Terseness in XML markup is of minimal importance. Several SGML language features were designed to minimize the amount of typing required to manually key in SGML documents.

How is XML defined?


Extensible Markup Language (XML)
Defines the syntax of XML.

XML Pointer Language (XPointer) and XML Linking Language (XLink)


Defines a standard way to represent links between resources.

Extensible Style Language (XSL)


Defines the standard stylesheet language for XML.

XML documents consist of


XML documents are composed of markup and content. There are six kinds of markup that can occur in an XML document:
elements entity references comments processing instructions marked sections document type declarations

Elements
Elements are the most common form of markup. Delimited by angle brackets <>
<Person> <FirstName>Janet</FirstName> <Middle>Q</Middle> <LastName>Leverling</LastName> <Address> <Address1>123 Elm</Address1> <Address2></Address2> <City>Pleasantville</City> <State>MA</State> <Zip>12345</Zip> </Address> </Person>

Empty elements have a modified syntax


<Person> </Person> or <Person/>

Attributes
Attributes are name-value pairs that occur inside start-tags after the element name.
<Person ID=0001> <FirstName>Janet</FirstName> <Middle>Q</Middle> <LastName>Leverling</LastName> <Address> <Address1>123 Elm</Address1> <Address2></Address2> <City>Pleasantville</City> <State>MA</State> <Zip>12345</Zip> </Address> </Person>

In XML, all attribute values must be quoted .

Entity References
Entities are used to represent these special characters.
&lt; produces the left angle bracket, < &gt; produces the right angle bracket, > &amp; produces the ampersand, & &apos; produces a single quote character (an apostrophe), ' &quot; produces a double quote character, "

It can be used to insert arbitrary Unicode characters into your document, ex : &#8474;

Comments
Comments begin with <!-- and end with -->. Comments can contain any data except the literal string --. Comments are not part of the textual content of an XML document.
Example : <!-- This is a comment -->

Processing Instructions
Processing instructions (PIs) are an escape hatch to provide information to an application. Like comments, they are not textually part of the XML document, but the XML processor is required to pass them to an application. Processing instructions have the form: <?name pidata?>.
Example : <?xml-stylesheet type="text/css" href="cd_catalog.css"?>

CDATA Sections
In a document, a CDATA section instructs the parser to ignore most markup characters. Consider a source code listing in an XML document.
<![CDATA[ *p = &q; b = (i <= 3); ]]>

Between the start of the section, <![CDATA[ and the end of the section, ]]>, all character data is passed directly to the application, without interpretation.

Document Type Declarations


Declarations allow a document to communicate meta-information to the parser about its content. Meta-information includes the allowed sequence and nesting of tags, attribute values and their types and defaults, the names of external files that may be referenced and whether or not they contain XML, the formats of some external (non-XML) data that may be referenced, and the entities that may be encountered. There are four kinds of declarations in XML:
element type declarations, attribute list declarations, entity declarations, and notation declarations

Element Type Declarations


Element type declarations identify the names of elements and the nature of their content.
A typical element type declaration looks like this: <!ELEMENT oldjoke (burns+, allen, applause?)> Element Declarations for Old Jokes
<!ELEMENT <!ELEMENT <!ELEMENT <!ELEMENT <!ELEMENT oldjoke burns allen quote applause (burns+, allen, applause?)> (#PCDATA | quote)*> (#PCDATA | quote)*> (#PCDATA)*> EMPTY>

<?xml version="1.0"?> <oldjoke> <burns>Say <quote>goodnight</quote>,Gracie.</burns> <allen><quote>Goodnight,Gracie.</quote></allen> <applause/> </oldjoke>

Attribute List Declarations (I)


Attribute list declarations identify which elements may have attributes, what attributes they may have, what values the attributes may hold, and what value is the default. Typical attribute list declaration looks like this:
<!ATTLIST oldjoke name ID #REQUIRED label CDATA #IMPLIED status ( funny | notfunny ) 'funny'>

Attribute List Declarations (II)


There are six possible attribute types:
CDATA : attributes are strings, any text is allowed. ID : the value of an ID attribute must be a name. All of the ID values used in a document must be different. IDREF or IDREFS : an IDREF attribute's value must be the value of a single ID attribute on some element in the document. ENTITY or ENTITIES : An ENTITY attribute's value must be the name of a single entity. NMTOKEN or NMTOKENS : Name token attributes are a restricted form of string attribute. In general, an NMTOKEN attribute must consist of a single word, but there are no additional constraints on the word, it doesn't have to match another attribute or declaration. A list of names : You can specify that the value of an attribute must be taken from a specific list of names. This is frequently called an enumerated type because each of the possible values is explicitly enumerated in the declaration.

Attribute List Declarations (III)


There are four possible default values:
#REQUIRED : The attribute must have an explicitly specified value on every occurrence of the element in the document. #IMPLIED : The attribute value is not required, and no default value is provided. If a value is not specified, the XML processor must proceed without one. "value" : An attribute can be given any legal value as a default. The attribute value is not required on each element in the document, and if it is not present, it will appear to be the specified default. #FIXED "value" : An attribute declaration may specify that an attribute has a fixed value. In this case, the attribute is not required, but if it occurs, it must have the specified value. If it is not present, it will appear to be the specified default. One use for fixed attributes is to associate semantics with an element. A complete discussion is beyond the scope of this lesson, but you can find several examples of fixed attributes in the XLink specification.

Entity Declarations (1)


There are three kinds of entities:
Internal Entities : Internal entities associate a name with a string of literal text. <!ENTITY ATI "ArborText, Inc."> Using &ATI; anywhere in the document will insert ArborText, Inc. at that location. Internal entities allow you to define shortcuts for frequently typed text or text that is expected to change, such as the revision status of a document. External Entities : External entities associate a name with the content of another file. External entities allow an XML document to refer to the contents of another file. External entities contain either text or binary data. <!ENTITY boilerplate SYSTEM "/standard/legalnotice.xml"> Using &boilerplate; will have insert the contents of the file /standard/legalnotice.xml at the location of the entity reference.

Entity Declarations (2)


Parameter entities : can only occur in the document type declaration. A parameter entity declaration is identified by placing % (percent-space) in front of its name in the declaration. The percent sign is also used in references to parameter entities, instead of the ampersand. Parameter entity references are immediately expanded in the document type declaration and their replacement text is part of the declaration, whereas normal entity references are not expanded. Parameter entities are not recognized in the body of a document.
<!ELEMENT burns <!ELEMENT allen (#PCDATA | quote)*> (#PCDATA | quote)*>

<!ENTITY % personcontent "#PCDATA | quote"> <!ELEMENT burns (%personcontent;)*> <!ELEMENT allen (%personcontent;)*>

Notation Declarations
Notation declarations identify specific types of external binary data. This information is passed to the processing application, which may make whatever use of it it wishes.
<!NOTATION GIF87A SYSTEM "GIF">

Including a Document Type Declaration


<?XML version="1.0" standalone="no"?> <!DOCTYPE chapter SYSTEM "dbook.dtd" [ <!ENTITY %ulink.module "IGNORE"> <!ELEMENT ulink (#PCDATA)*> <!ATTLIST ulink xml:link CDATA #FIXED "SIMPLE" xml-attributes CDATA #FIXED "HREF URL" URL CDATA #REQUIRED> ]> <chapter>...</chapter>

Validity
Given the preceding discussion of type declarations, it follows that some documents are valid and some are not. There are two categories of XML documents: well-formed and valid.
Well-formed Documents : A document can only be wellformed if it obeys the syntax of XML. A document that includes sequences of markup characters that cannot be parsed or are invalid cannot be well-formed. If a document is not well-formed, it is not XML. Valid Documents : A well-formed document is valid only if it contains a proper document type declaration and if the document obeys the constraints of that declaration (element sequence and nesting is valid, required attributes are provided, attribute values are of the correct type, etc.).

Validity
It must meet all of the following conditions
1. 2. The document instance must conform to the grammar of XML documents. The replacement text for all parameter entities referenced inside a markup declaration consists of zero or more complete markup declarations. No attribute may appear more than once on the same starttag. String attribute values cannot contain references to external entities. Non-empty tags must be properly nested. Parameter entities must be declared before they are used. All entities except the following: amp, lt, gt, apos, and quot must be declared. A binary entity cannot be referenced in the flow of content, it can only be used in an attribute declared as ENTITY or ENTITIES. Neither text nor parameter entities are allowed to be recursive, directly or indirectly.

3. 4. 5. 6. 7. 8.

9.

XLink
XLink introduce a standard linking model for XML. A link expresses a relationship between resources. A resource is any location (an element, or its content, or some part of its content, for example) that is addressed in a link. The exact nature of the relationship between resources depends on both the application that processes the link and semantic information supplied.

Some highlights of XLink


XLink gives you control over the semantics of the link. XLink introduces Extended Links. Extended Links can involve more than two resources. XPointer introduces Extended Pointers (XPointers). XPointers provide a sophisticated method of locating resources. In particular, XPointers allow you to locate arbitrary resources in a document, without requiring that the resource be identified with an ID attribute.

Simple Links
<link xml:link="simple" href="locator">Link Text</link>

A Simple Link identifies a link between two resources, one of which is the content of the linking element itself. This is an in-line link. The locator identifies the other resource. The locator may be a URL, a query, or an Extended Pointer.

Extended Links
Extended Links allow you to express relationships between more than two resources:
<elink xml:link="extended" role="annotation"> <locator xml:link="locator" href="text.loc">The Text </locator> <locator xml:link="locator" href="annot1.loc">Annotations </locator> <locator xml:link="locator" href="annot2.loc"> More Annotations</locator> <locator xml:link="locator" href="litcrit.loc"> Literary Criticism</locator> </elink>

This example shows how the relationships between a literary work, annotations, and literary criticism of that work might be expressed. Note that this link is separate from all of the resources involved.

XML Mappings in Excel 2003


Microsoft Office Excel 2003 improves support for using native XML by enabling you to add your own XML Schema Definition (XSD) to a workbook. This creates an XML map that you can use to make data more meaningful upon importing or exporting data.
1. 2. 3. 4. Create a map between an Excel spreadsheet and an XML structure Use that map to import subsequent XML data to that same structure Use that map to export XML data from the spreadsheet, that conforms to that XML schema Persist and reuse that map for subsequent import and export operations

Mapping process
Adding an XSD file to an Excel workbook Once you add the XSD file, Excel creates an XML map in the XML Source task pane Excel also uses this map to manage the relationship between those mapped ranges and the elements in the XML schema. Excel also uses this map to manage the relationship between those mapped ranges and the elements in the XML schema.
A workbook can contain many XML maps where each map is an independent entity. Likewise, you can also have multiple maps refer to the same schema. When you import or export XML data, Excel uses the map to relate the contents of a mapped range to elements in the schema.

Adding an XML Map to a Workbook


On the View menu, click Task Pane to display the XML Source task pane. OROn the Data menu, point to XML, and then click XML Source. Click XML Maps and then Add. Go to the schema file, click Open, and then click OK.

Example

Mapping with the XML Source Task


The XML Source task pane displays the XML schemas in the workbook in a tree view. You can map elements by dragging them onto the worksheet, or you can right-click each element and choose Map element. You can select non-adjacent elements by clicking one element, holding down the CTRL key, and clicking additional elements. Once you select the elements, drag them to the worksheet location where you want them to appear. If the element is a repeating element, Excel creates an XML List in the cell where you added the element.

Importing Data into a Mapped Range


1. Select a cell in the mapped range into which you want to import XML data. 2. On the Data menu, point to XML, and then click Import. 3. In the Look in list, click the drive, folder, or Internet location that contains the XML data file you want to import. 4. In the folder list, locate and open the folder that contains the file. 5. Click the file, and then click Import.

XML Mapping Scenarios


1. Copy and paste the XML and XSD listings into separate files using a text editor such as Notepad. 2. Import the XSD data into the XML Source task pane to create a map. 3. Drag and drop the designated element(s) of the map onto the worksheet cell. 4. Import the data from the XML file.

XML Mapping Scenarios


1. Copy and paste the XML and XSD listings into separate files using a text editor such as Notepad. 2. Import the XSD data into the XML Source task pane to create a map. 3. Drag and drop the designated element(s) of the map onto the worksheet cell. 4. Import the data from the XML file.

XML Mapping Scenarios


1. Copy and paste the XML and XSD listings into separate files using a text editor such as Notepad. 2. Import the XSD data into the XML Source task pane to create a map. 3. Drag and drop the designated element(s) of the map onto the worksheet cell. 4. Import the data from the XML file.

CSS - What is CSS?


CSS stands for Cascading Style Sheets Styles define how to display HTML elements Styles are normally stored in Style Sheets Styles were added to HTML 4.0 External Style Sheets can save you a lot of work External Style Sheets are stored in CSS files Multiple style definitions will cascade into one

Styles Solve a Common Problem


HTML tags were originally designed to define the content of a document. They were supposed to say "This is a header", "This is a paragraph", "This is a table", by using tags like <h1>, <p>, <table>, and so on. The layout of the document was supposed to be taken care of by the browser, without using any formatting tags. Netscape and Internet Explorer - continued to add new HTML tags and attributes (like the <font> tag and the color attribute) to the original HTML specification, it became more and more difficult to create Web sites Both Netscape 4.0 and Internet Explorer 4.0 support Cascading Style Sheets.

Cascading Order
What style will be used when there is more than one style specified for an HTML element? Generally speaking we can say that all the styles will "cascade" into a new "virtual" Style Sheet by the following rules, where number four has the highest priority:
Browser default External Style Sheet Internal Style Sheet (inside the <head> tag) Inline Style (inside HTML element)

Syntax
The CSS syntax is made up of three parts: a selector, a property and a value:
selector {property: value}

The property and value are separated by a colon and surrounded by curly braces:
body {color: black}

If the value is multiple words, put quotes around the value:


p {font-family: "sans serif"}

If you wish to specify more than one property, you must separate each property with a semi-colon.
p {text-align:center;color:red}

Syntax (2)
To make the style definitions more readable, you can describe one property on each line, like this:
P { text-align: center; color: black; font-family: arial }

You can group selectors :


h1,h2,h3,h4,h5,h6 { color: green }

Syntax (3)
The class Selector : With the class selector you can define different styles for the same type of HTML element.
p.right {text-align: right} p.center {text-align: center}

<p class="right"> This paragraph will be right-aligned. </p> <p class="center"> This paragraph will be center-aligned. </p>

CSS Comments
You can insert comments in CSS to explain your code, which can help you when you edit the source code at a later date. A comment will be ignored by the browser. A CSS comment begins with "/*", and ends with "*/", like this:
/* This is a comment */ p { text-align: center; /* This is another comment */ color: black; font-family: arial }

Example 1 with HTML


Example-1.html :
<html> <head> <link rel="stylesheet" type="text/css" href="example-1.css" /> </head> <body> <h1>This header is 36 pt</h1> <h2>This header is blue</h2> <p>This paragraph has a left margin of 50 pixels</p> </body> </html>

Example-1.css:
h1 {font-size: 36pt} h2 {color: blue} p {margin-left: 50px}

Example 2 with XML


xml-ex-1.xml :
<?xml version='1.0'?> <?xml-stylesheet type="text/css" href="css-ex-1.css"?> <CATALOG xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>USA</COUNTRY> <COMPANY>Columbia</COMPANY> <PRICE>10.9</PRICE> <YEAR>1985</YEAR> </CD> <CD> <TITLE>Hide your heart</TITLE> <ARTIST>Bonnie Tyler</ARTIST> <COUNTRY>UK</COUNTRY> <COMPANY>CBS Records</COMPANY> <PRICE>9.9</PRICE> <YEAR>1988</YEAR> </CD> </CATALOG>

Example 2 with XML


css-ex-1.css :
TITLE { magin-top : 7in; magin-bottom :7in; magin-left : 1.5in; magin-right : 1in; background-color:white; display:block } ARTIST { font-family: Arial, Helvetica, sans-serif; font-size:32pt; width: 30em; color:red } COUNTRY { font-family: Arial, Helvetica, sans-serif; color:blue }

CSS Background Properties


CSS Background properties define the background effects of an element.
Property Description Values background A shorthand property for setting all background properties in one declaration Sets whether a background image is fixed or scrolls with the rest of the page Sets the background color of an element Sets an image as the background Sets the starting position of a background image

background-color, backgroundimage, background-repeat background-attachment, background-position


scroll fixed

backgroundattachment backgroundcolor backgroundimage backgroundposition

color-rgb, color-hex, color-name,


transparent

url, none
top left, top center, top right, center left, center center, center right, bottom left, bottom center, bottom right, x-% y-%, x-pos yRepeat, repeat-x, repeat-y, norepeat

pos
backgroundrepeat Sets if/how a background image will be repeated

CSS Background Properties (example)


<html> <head> <style type="text/css"> h1 {background-color: #00ff00} h2 {background-color: transparent} body {background-image: url('C:\Documents and Settings\My Documents\My Pictures\Logo-Datic.bmp')} p {background-color: rgb(250,0,255)} </style> </head> <body> <h1>This is header 1</h1> <h2>This is header 2</h2> <p>This is a paragraph</p> </body> </html>

CSS Text Properties


CSS Text properties define the appearance of text.
Property color direction letter-spacing text-align text-decoration text-indent text-shadow text-transform unicode-bidi white-space word-spacing Sets how white space inside an element is handled Increase or decrease the space between words Controls the letters in an element Description Sets the color of a text Sets the text direction Increase or decrease the space between characters Aligns the text in an elem. Adds decoration to text Indents the first line of text Possible Values color Ltr, rtl normal length Left, right, center, justify None, underline, overline, line-through, blink Length, % None, color, length None, capitalize, uppercase, lowercase Normal, embed, bidioverride Normal, pre, nowrap Normal, length

CSS Text Properties (example)


<html> <head> <style type="text/css"> h1 {color: #00ff00} h2 {color: #dda0dd} p {color: rgb(0,0,255)} </style> </head> <body> <h1>This is header 1</h1> <h2>This is header 2</h2> <p>This is a paragraph</p> </body> </html>

CSS Font Properties


CSS Font properties define the font in text.
Property font Description A shorthand property for setting all of the properties A prioritized list of Sets the size of a font aspect value Condenses or expands the current fontfamily Sets the style Values font-style, font-variant, font-weight, font-size/line-height, font-family, caption, icon, menu, message-box, small-caption, status-bar family-name, generic-family xx-small, x-small, small, medium, large, x-large, xx-large, smaller, larger, length None, number Normal, wider, narrower, ultracondensed, extra-condensed, condensed, semi-condensed, semiexpanded, expanded, extra-expanded Normal, italic, oblique Normal, small-caps Sets the weight of a font Normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900

font-family font-size

font-size-adjust font-stretch

font-style font-variant font-weight

CSS Font Properties (example)


<html> <head> <style type="text/css"> h3 {font-family: times} p {font-family: courier} p.sansserif {font-family: sans-serif} </style> </head> <body> <h3>This is header 3</h3> <p> This is a paragraph</p> <p class="sansserif"> This is a paragraph</p> </body> </html>

CSS Border Properties


CSS Border properties define the borders an element.
Property border Description A shorthand property for setting all of the properties for the four borders in one declaration A shorthand property for setting all of the properties for the bottom border Sets the color of the bottom border Sets the style of the bottom border Sets the width of the bottom border Sets the color of the four borders A shorthand property for setting all of the properties for the left border Sets the color of the left border Sets the style of the left border Sets the width of the left border A shorthand property for setting all of the properties for the right border Sets the color of the right border Sets the style of the right border Sets the width of the right border Sets the style of the four borders, can have from one to four styles A shorthand property for setting all of the properties for the top border Values border-width, border-style, border-color border-bottom-width, borderstyle, border-color border-color border-style Thin, medium, thick, length Color border-left-width, border-style, border-color border-color border-style Thin, medium, thick, length border-right-width, border-style, border-color border-color border-style Thin, medium, thick, length None, hidden, dotted, dashed, solid, double, groove, ridge border-top-width, border-style border-color

border-bottom border-bottom-color border-bottom-style border-bottom-width border-color border-left border-left-color border-left-style border-left-width border-right border-right-color border-right-style border-right-width border-style

border-top

CSS Border Properties (example)


<html> <head> <style type="text/css"> p.dotted {border-style: dotted} p.dashed {border-style: dashed} </style> </head> <body> <p>The "border-style" property is not recognized by Netscape 4.</p> <p>Netscape 6 supports all border styles.</p> <p>Internet Explorer 5.5 supports all border styles. Internet Explorer 4.0 - 5.0 do not support the "dotted" and "dashed" values</p> <p class="dotted"> A dotted border</p> <p class="dashed"> A dashed border</p> </body> </html>

CSS Margin Properties


define the space around elements.
Property margin Description A shorthand property for setting the margin properties in one declaration Sets the bottom margin of an element Sets the left margin of an element Sets the right margin of an element Sets the top margin of an element Values margin-top margin-right margin-bottom margin-left auto length % auto length % auto length % auto length %

margin-bottom

margin-left

margin-right

margin-top

CSS Margin Properties (example)


<html> <head> <style type="text/css"> p.margin {margin-left: 2cm} </style> </head> <body> <p> This is a paragraph This is a paragraph This is a paragraph This is a paragraph </p> <p class="margin"> This is a paragraph with a left margin This is a paragraph with a left margin </p> </body> </html>

CSS Padding Properties


define the space between the element border and the element content.
Property padding Description Values A shorthand property for padding-top setting all of the padding-right padding properties in padding-bottom one declaration padding-left Sets the bottom padding of an element Sets the left padding of an element length % length %

padding-bottom padding-left padding-right padding-top

Sets the right padding of length an element % Sets the top padding of an element length %

CSS Padding Properties (example)


<html> <head> <style type="text/css"> td {padding-left: 2cm} </style> </head> <body> <table border="1"> <tr> <td> This is a tablecell with a left padding </td> </tr> </table> </body> </html>

CSS List Properties


allow you to change between different list-item markers, set an image as a list-item marker, and set where to place a list-item marker.
Property list-style Description A shorthand property for setting all of the properties for a list in one declaration Sets an image as the list-item marker Places the list-item marker in the list Sets the type of the list-item marker Values list-style-type list-style-position list-style-image none url inside outside None, disc, circle, square, decimal, decimal-leading-zero, lower-roman, upperroman, lower-alpha, upper-alpha, lowergreek, lower-latin, upper-latin, hebrew armenian Auto, length

list-style-image list-style-position list-style-type

marker-offset

CSS List Properties (example)


<html> <head> <style type="text/css"> ul.disc { list-style-type: disc } ul.circle { list-style-type: circle } ul.square { list-style-type: square } ul.none { list-style-type: none } </style> </head> <body> <ul class="disc"> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ul> <ul class="circle"> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ul> <ul class="square"> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ul> <ul class="none"> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ul> </body> </html>

CSS Dimension Properties


The Dimension properties allow you to control the height and width of an element. It also allows you to increase the space between two lines.
Property height line-height max-height max-width min-height min-width width Description Sets the height of an element Sets the distance between lines Sets the maximum height of an element Sets the maximum width of an element Sets the minimum height of an element Sets the minimum width of an element Sets the width of an element Values Auto, length, % Normal, number, length, % None, length, % None, length, % Length, % Length, % Auto, %, length

CSS Dimension Properties (example)


<html> <head> <style type="text/css"> img.normal { height: auto; width: auto } img.big { height: 80px; width: 100px } img.small { height: 30px; width: 50px } </style> </head> <body> <p><b>Note:</b> Netscape 4 does not support the "height" property, and the "width" property does not work on images.</p> <img class="normal" src="back.gif" width="72" height="40"> <br><br> <img class="big" src="back.gif" width="72" height="40"> <br><br> <img class="small" src="back.gif" width="72" height="40"> </body> </html>

CSS Classification Properties


The Classification properties allow you to control how to display an element, set where an image will appear in another element, position an element relative to its normal position, position an element using an absolute value, and how to control the visibility of an element.
Property clear Description Sets the sides of an element where other floating elements are not allowed Specifies the type of cursor to be displayed Sets how/if an element is displayed Values Left, right, both, none

cursor

url, auto, crosshair, default, pointer, move, eresize, ne-resize, nw-resize, n-resize, se-resize, sw-resize, s-resize, w-resize, text, wait, help None,inline, block, list-item, run-in, compact, marker, table, inline-table, table-row-group, tableheader-group, table-footer-group, table-row, table-column-group, table-column, table-cell, table-caption Left, right, none Static, relative, absolute, fixed

display

float position

Sets where an image or a text will appear in another element Places an element in a static, relative or fixed position Sets if an element should be visible or invisible

visibility

Visible, hidden, collapse

CSS Classification Properties (example)


<html> <head> <style type="text/css"> div {display: none} p {display: inline} </style> </head> <body> <div> The div section is invisible </div> <p> With the value of "inline" there should be </p> <p> no distance between the two paragraphs. </p> </body> </html>

CSS Positioning Properties


define the position of an element.
Property bottom clip left overflow position right top Description Specifies the bottom edge of an element Sets the shape of an element Specifies the left edge of an element Sets what happens if the content of an element overflow its area Places an element in a static, relative, absolute or fixed position Specifies the right edge of an element Sets how far the top edge of an element is above/below the top edge of the parent element Sets the vertical alignment of an element Values Auto, %, length Shape, auto Auto, %, length Visible, hidden, scroll, auto Static, relative, absolute, fixed Auto, %, length Auto, %, length

verticalalign

Baseline, sub, super, top, text-top, middle, bottom, text-bottom, length, % Auto, number

z-index

Sets the stack order of an element

CSS Positioning Properties (example)


<html> <head> <style type="text/css"> img { position:absolute; clip:rect(0px 50px 200px 0px) } </style> </head> <body> <p><b>Note:</b> Netscape 4 does not support the "clip" property.</p> <p>Note that this property is cutting the image. The width and the height properties (or attributes) decreases the image.</p> <p><img border="0" src="bookasp20.gif" width="120" height="151"></p> </body> </html>

CSS Pseudo-classes
Pseudo-classes are used in CSS to add different effects to some selectors, or to a part of some selectors.
Pseudo- NN IE classes active hover link visited :firstchild :lang 7.1 4.0 4.0 7.0 4.0 4.0 3.0 3.0 W3C CSS1 CSS1 CSS1 CSS1 CSS2 CSS2 Purpose Adds special style to a selected link Adds special style to a link when you mouse over it Adds special style to an unvisited link Adds special style to a visited link Adds special style to an element that is the first child of some other element Allows the author to specify a language to use in a specified element

CSS Pseudo-classes (example)


<html> <head> <style type="text/css"> a:link {color: #FF0000} a:visited {color: #00FF00} a:hover {color: #FF00FF} a:active {color: #0000FF} </style> </head> <body> <p><b><a href="default.asp" target="_blank">This is a link</a></b></p> <p><b>Note:</b> a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective!!</p> <p><b>Note:</b> a:active MUST come after a:hover in the CSS definition in order to be effective!!</p> </body> </html>

XSL
XSL stands for eXtensible Stylesheet Language. The World Wide Web Consortium (W3C) started to develop XSL because there was a need for an XML based Stylesheet Language. CSS - HTML Style Sheets :
HTML uses predefined tags and the meanings of tags are well understood. The <table> element defines a table and a browser knows how to display it. Adding styles to HTML elements is also simple. Telling a browser to display an element in a special font or color, is easily done with CSS.

XSL
XSL stands for eXtensible Stylesheet Language. The World Wide Web Consortium (W3C) started to develop XSL because there was a need for an XML based Stylesheet Language. CSS - HTML Style Sheets :
HTML uses predefined tags and the meanings of tags are well understood. The <table> element defines a table and a browser knows how to display it. Adding styles to HTML elements is also simple. Telling a browser to display an element in a special font or color, is easily done with CSS.

XML and HTML


Data in XML

StyleSheets

Layout in HTML

XSL Transformations
XML

XML

XSL Transformation

Plain Text

WML

PDF

HTML

SGML

XML Deployment
System to System Application to Application Client to Server

Technology Leaders Driving XML


Application Application Integration Integration Native XML Native XML Applications Applications

e-Commerce e-Commerce

Content Content Management Management

XSL - XML Style Sheets


XML does not use predefined tags (we can use any tags we like) and the meanings of these tags are not well understood. The <table> could mean an HTML table or a piece of furniture, and a browser does not know how to display it. There must be something in addition to the XML document that describes how the document should be displayed; and that is XSL!
Input XML document Input XML document

XSLT Transformation

Formatting Process

Resultant Document

XSL - More Than a Style Sheet Language


XSL consists of three parts:
XSLT is a language for transforming XML documents XPath is a language for defining parts of an XML document XSL-FO is a language for formatting XML documents

XSL as a set of languages that can :


transform XML into XHTML, filter and sort XML data, define parts of an XML document, format XML data based on the data value, like displaying negative numbers in red, and output XML data to different media, like screens, paper, or voice.

XSLT - XSL Transformations


XSLT is the most important part of the XSL Standards. It is the part of XSL that is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML. XSLT can also add new elements into the output file, or remove elements. It can rearrange and sort elements, and test and make decisions about which elements to display, and a lot more. A common way to describe the transformation process is to say that XSLT transforms an XML source tree into an XML result tree.

How does it Work?


In the transformation process, XSLT uses XPath to define parts of the source document that match one or more predefined templates. When a match is found, XSLT will transform the matching part of the source document into the result document. The parts of the source document that do not match a template will end up unmodified in the result document. Not all Internet browsers have full support for XSLT.

Support for XSLT


Internet Explorer 5 is Bad Internet Explorer 6 is Better Netscape 6 isn't fully supporting the official W3C XSLT Recommendation. However, most of the examples in this tutorial will also work in Netscape 6. Netscape 7 supports the official W3C XSLT Recommendation. Internet Explorer MSXML Parser : MSXML Parser
3.0 is the XML parser that is shipped with IE 6.0 and Windows XP.

Correct Style Sheet Declaration


The root element that declares the document to be an XSL style sheet is <xsl:stylesheet> or <xsl:transform>. Example :
<xsl:stylesheet version="1.0"xmlns:xsl= "http://www.w3.org/1999/XSL/Transform">

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

Start with your XML Document


We want to transform the following XML document ("cdcatalog.xml") into XHTML:
<?xml version="1.0" encoding="ISO-8859-1"?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> . . . </catalog>

Create an XSL Style Sheet ("cdcatalog.xsl")


<?xml version="1.0" encoding="ISO-8859-1"?> <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 bgcolor="#9acd32"> <th align="left">Title</th> <th 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> (http://www.w3.org/TR/WD-xsl) </xsl:stylesheet>

Link the XSL Style Sheet to the XML Document


Finally, add an XSL Style Sheet reference to your XML document ("cdcatalog.xml"):
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> . . . </catalog>

XSLT uses Templates


The <xsl:template> element contains rules to apply when a specified node is matched. The match attribute is used to associate the template with an XML element.
<?xml version="1.0" encoding="ISO-8859-1"?> <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 bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> My CD Collection <tr> <td>.</td> Title Artist <td>.</td> </tr> . . </table> </body> </html> </xsl:template> </xsl:stylesheet>

XSLT uses Templates


Since the style sheet is an XML document itself, the document begins with an xml declaration: <?xml version="1.0" encoding="ISO-8859-1"?>. The <xsl:stylesheet> tag defines the start of the style sheet. The <xsl:template> tag defines the start of a template. The match="/" attribute associates (matches) the template to the root (/) of the XML source document. The rest of the document contains the template itself, except for the last two lines that defines the end of the template and the end of the style sheet.

The <xsl:value-of> Element


The <xsl:value-of> element can be used to select the value of an XML element and add it to the output stream of the transformation:
<?xml version="1.0" encoding="ISO-8859-1"?> <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 bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <tr> <td><xsl:value-of Select="catalog/cd/title"/></td> <td><xsl:value-of select="catalog/cd/artist"/></td> </tr> </table> </body> </html> </xsl:template> </xsl:stylesheet>

The <xsl:for-each> Element


The XSL <xsl:for-each> element can be used to select every XML element of a specified node set:
<?xml version="1.0" encoding="ISO-8859-1"?> <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 bgcolor="#9acd32"> <th>Title</th> <th>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>

Filtering the Output


We can filter the output from an XML file by adding a criterion to the select attribute in the <xsl:for-each> element.
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">

Legal filter operators are: = (equal) != (not equal) &lt; less than &gt; greater than

The <xsl:for-each> Element (example)


<?xml version="1.0" encoding="ISO-8859-1"?> <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 bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd[artist='Bob Dylan']"> <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>

The <xsl:sort> element is used to sort the output.


To output the XML file as an XHTML file, and sort it at the same time, simply add a sort element inside the for-each element in your XSL file:
<?xml version="1.0" encoding="ISO-8859-1"?> <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 bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd"> <xsl:sort select="artist"/> <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>

The <xsl:if> element


To put a conditional if test against the content of the file, simply add an <xsl:if> element to your XSL document like this:
<?xml version="1.0" encoding="ISO-8859-1"?> <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 bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd"> <xsl:if test="price &gt; 10"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </tr> </xsl:if> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

The <xsl:choose> element


To insert a conditional choose test against the content of the XML file, simply add the <xsl:choose>, <xsl:when>, and <xsl:otherwise> elements to your XSL document like this: <xsl:choose> <xsl:when test="price &gt; 10"> ... some code ... </xsl:when> <xsl:otherwise> ... some code .... </xsl:otherwise> </xsl:choose>

The <xsl:choose> element (example)


<?xml version="1.0" encoding="ISO-8859-1"?> <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 bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd"> <tr> <td><xsl:value-of select="title"/></td> <xsl:choose> <xsl:when test="price &gt; 10"> <td bgcolor="#ff00ff"> <xsl:value-of select="artist"/></td> </xsl:when> <xsl:otherwise> <td><xsl:value-of select="artist"/></td> </xsl:otherwise> </xsl:choose> </tr> </xsl:for-each> </table> </body></html> </xsl:template></xsl:stylesheet>

The <xsl:apply-templates> Element


The <xsl:apply-templates> element applies a template rule to the current element or to the current element's child nodes.
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="cd"> <p> <xsl:apply-templates select="title"/> <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 select="."/></span> <br /> </xsl:template> </xsl:stylesheet>

A JavaScript Solution
A more versatile solution would be to use a JavaScript to do the XML to XHTML transformation. By using JavaScript, we can: do browser-specific testing use different style sheets according to browser and user needs One of the design goals for XSLT was to make it possible to transform data from one format to another, supporting different browsers and different user needs.

A JavaScript Solution (Example - 1)


Take a new look at the XML document that you saw in the previous chapters:
<?xml version="1.0" encoding="ISO-8859-1"?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> . . . </catalog>

A JavaScript Solution (Example - 2)


And the accompanying XSL style sheet :
<?xml version="1.0" encoding="ISO-8859-1"?> <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 bgcolor="#9acd32"> <th align="left">Title</th> <th 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>

A JavaScript Solution (Example - 3)


Here is the source code needed to transform the XML file to XHTML on the client:
<html> <body> <script type="text/javascript"> // Load XML var xml = new ActiveXObject("Microsoft.XMLDOM") xml.async = false xml.load("cdcatalog.xml") // Load XSL var xsl = new ActiveXObject("Microsoft.XMLDOM") xsl.async = false xsl.load("cdcatalog.xsl") // Transform document.write(xml.transformNode(xsl)) </script> </body> </html>

A JavaScript Solution (Example - 4)


Here is the source code needed to transform the XML file to XHTML on the server:
<% 'Load XML set xml = Server.CreateObject("Microsoft.XMLDOM") xml.async = false xml.load(Server.MapPath("cdcatalog.xml")) 'Load XSL set xsl = Server.CreateObject("Microsoft.XMLDOM") xsl.async = false xsl.load(Server.MapPath("cdcatalog.xsl")) 'Transform file Response.Write(xml.transformNode(xsl)) %>

XSLT Elements (1)


Element applyimports applytemplates attribute attributeset calltemplate choose comment copy copy-of decimalformat element Description Applies a template rule from an imported style sheet Applies a template rule to the current element or to the current element's child nodes Adds an attribute Defines a named set of attributes Calls a named template Used in conjunction with <when> and <otherwise> to express multiple conditional tests Creates a comment node in the result tree Creates a copy of the current node (without child nodes and attributes) Creates a copy of the current node (with child nodes and attributes) Defines the characters and symbols to be used when converting numbers into strings, with the format-number() function Creates an element node in the output document IE 6.0 5.0 5.0 6.0 6.0 5.0 5.0 5.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0 NN

5.0

6.0

XSLT Elements (2)


Element fallback for-each if import Description Specifies an alternate code to run if the processor does not support an XSLT element Loops through each node in a specified node set Contains a template that will be applied only if a specified condition is true Imports the contents of one style sheet into another. Note: An imported style sheet has lower precedence than the importing style sheet Includes the contents of one style sheet into another. Note: An included style sheet has the same precedence as the including style sheet Declares a named key that can be used in the style sheet with the key() function Writes a message to the output (used to report errors) Replaces a namespace in the style sheet to a different namespace in the output Determines the integer position of the current node and formats a number Specifies a default action for the <choose> element Defines the format of the output document IE 6.0 5.0 5.0 6.0 6.0 6.0 6.0 NN

include

6.0

6.0

key message namespace -alias number otherwise output

6.0 6.0 6.0 6.0 5.0 6.0

6.0 6.0

6.0 6.0 6.0

XSLT Elements (3)


Element param preservespace processinginstruction sort strip-space stylesheet template text transform value-of variable when with-param Description Declares a local or global parameter Defines the elements for which white space should be preserved Writes a processing instruction to the output Sorts the output Defines the elements for which white space should be removed Defines the root element of a style sheet Rules to apply when a specified node is matched Writes literal text to the output Defines the root element of a style sheet Extracts the value of a selected node Declares a local or global variable Specifies an action for the <choose> element Defines the value of a parameter to be passed into a template IE 6.0 6.0 5.0 6.0 6.0 5.0 5.0 5.0 6.0 5.0 6.0 5.0 6.0 NN 6.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0

XSLT Functions
Here is the source code needed to transform the XML file to XHTML on the server:
Name current() document() elementavailable() formatnumber() functionavailable() generateid() key() systemproperty() unparsedentity-uri() Description Returns the current node Used to access the nodes in an external XML document Tests whether the element specified is supported by the XSLT processor Converts a number into a string Tests whether the function specified is supported by the XSLT processor Returns a string value that uniquely identifies a specified node Returns a node-set using the index specified by an <xsl:key> element Returns the value of the system properties Returns the URI of an unparsed entity

You might also like