5 xsl (formatting xml documents)

Post on 16-Apr-2017

2.209 Views

Category:

Education

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Extensible Stylesheet Language (XSL)

Atul Kahate

akahate@gmail.com

XSL | Atul Kahate 2

Agenda Stylesheets Cascading Style Sheets (CSS) Extensible Stylesheet Language

(XSL) XSL Transformations (XSLT)

XSL | Atul Kahate 3

Style Sheets Basics XML concentrates on the structure of

information Normally, the appearance of information

is secondary Sometimes, it is necessary to format XML

information so as to view it in a particular manner

This is called as styling an XML document

XSL | Atul Kahate 4

Style Sheets Formatting instructions for XML

documents are organized/grouped These organized instructions are

called as style sheets A style sheet can be applied to

view a particular XML document in a specific format

XSL | Atul Kahate 5

Standards For XML Styling Two main standards Developed by W3C

CSS (Cascading Style Sheet) XSL (XML Stylesheet Language)

XSL | Atul Kahate 6

CSS versus XSL CSS Approach

XSL Approach

XML Documen

tCSS Style

Sheet

XML Documen

tXSL Style

Sheet

HTMLDocumen

t

XSL | Atul Kahate 9

CSS Terminology Style sheets are used to define rules A rule is composed of two parts

Selector (Element to which the rule applies) Declaration (Attributes and values)

ExamplePARA {FONT: 12pt “Times New Roman”}

Here, PARA is the selector, the rest is the declaration

XSL | Atul Kahate 11

DTD and Stylesheet Example - 1 Consider a MEMO DTD…<!DOCTYPE MEMODTD [<!ELEMENT MEMO (TO, FROM, SUBJECT, BODY)><!ELEMENT TO (#PCDATA)><!ELEMENT FROM (#PCDATA)><!ELEMENT SUBJECT (#PCDATA)><!ELEMENT BODY (#PCDATA)>]>

XSL | Atul Kahate 12

DTD and Stylesheet Example - 2 Suppose we want to do the following

Display the elements TO, FROM, and SUBJECT in bold along with their contents

Display the entire memo in Times New Roman font with size as 12 points, and margin of 1 line

Use the stylesheet as follows

XSL | Atul Kahate 13

DTD and Stylesheet Example - 3 CSS declaration follows…MEMO {font-family: “Times New Roman”, “Book Antigua”,

serif;font-size: 12pt;margin: lin}

TO, FROM, SUBJECT {font-weight: bold}

XSL | Atul Kahate 14

Sample XML Document<?xml version=“1.0”?><?xml-stylesheet href=“article.css” type=“text/css”?><article>

<title> Style Sheets Example </title><section>

<p> This example illustrates how style sheets can be applied to XML documents. </p></section><section>

<title> Styling </title><p> Style sheets format XML documents in a desired manner.

</p></section>

</article>

XSL | Atul Kahate 15

Corresponding CSS Document/* a simple style sheet */article{

font-family: Palatino, Garamond, “Times New Roman”, serif;font-size: 18pt;margin: 5px

}article, p, title{

display: block;margin-bottom: 10px

}article title{

font-size: 24pt;font-weight: bold

}section title{

font-size: 20pt;font-style: italic

}

XSL | Atul Kahate 16

Output in Web Browser

Introduction to XSLT Concepts

XSL | Atul Kahate 22

Programming Language Classification Imperative Languages

Set some variables, call methods, use operators that change value, etc

C, C++, Java, C# Declarative or Functional Languages

Perform logical operations using declarations, rather than writing code

Prolog, XSLT

XSL | Atul Kahate 23

Recursion Using recursion, imperative

languages such as Java can behave like declarative languages such as XSLT

Examplepublic int factorial(int number) { if (number <= 1) return 1; return number * factorial(number-1);}

XSL | Atul Kahate 24

Recursion Illustrated

XSL | Atul Kahate 25

Recursion and XSL: When? When we have a set of repeating values in the

source XML and we want the transformation result to reflect something about all of those values. For example, if you have a catalog of items in XML and want to present those items along with the price for all of the items, you would have to find that total price using a recursive template.

When the source XML contains a number x in a tag, for example <countTo number="5"/>, and you want to present some information that same x number of times in the transformation output.

XSL Terminologies

XSL, XSLT, XSLFO, XPath, XPointer, Stylesheet,

Template, …

XSL | Atul Kahate 27

XSL (XML Stylesheet Language) Two parts

XSLT (XSL Transformation) XSL-FO (XSL Formatting Objects)

XSLFO is similar to CSS, quite complex

We will discuss XSLT in detail, XSL-FO in brief

XSL | Atul Kahate 28

XPath Allows searching and navigation of

XML documents Can specify which parts of an XML

document we want to transform Used heavily in XSLT for searching

of information

XSL | Atul Kahate 29

XSLT Usage Styling Add elements specific to viewing (e.g. logo) Create new content from existing one (e.g.

TOC) Present information with the right level of

details (e.g. overview for managers, details for staff)

Convert between different DTDs/schemas or different versions of a DTD/schema

Transform XML documents into HTML for compatibility with older browsers

XSL | Atul Kahate 30

XSLT Stylesheets An XSLT stylesheet consists of a series

of templates, together with instructions based on XPath

Tell an XSLT processor how to match the template against the nodes in an XML input document

For each template, the processor reads the input document for all matching patterns and produces an output document

See next slide

XSL | Atul Kahate 31

XSLT Processing ConceptInput XML document XSLT

Processor

Output XML document

XSLT Template

XSLT Stylesheet

XSLT Basics

XSL | Atul Kahate 33

Simple XSLT Example XML (test.xml)

<?xml version="1.0"?><?xml-stylesheet href="test.xsl" type="text/xsl"?><xslTutorial> <title>XSL</title> <author>John Smith</author> </xslTutorial>

XSLT (test.xsl)<?xml version="1.0" ?><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

version="1.0"><xsl:template match="/"> <H1><xsl:value-of select="//title"/></H1> <H2><xsl:value-of select="//author"/></H2> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 34

Change to the XML The XML document has an <xml-

stylesheet> tag, which informs the parser that we want to use an XSLT stylesheet to process this XML file before displaying its contents

XSL | Atul Kahate 35

Now look at the XSL The XSLT stylesheet is also a well-

formed XML document The <xsl:stylesheet> element has

two attributes Version specifies the XSLT

specifications version Declares the namespace

XSL | Atul Kahate 36

Question What if our XML document has

multiple occurrences of the title and author tags? We would still see only the first

occurrence, since we have not yet seen the recursion part of XSLT

XSL | Atul Kahate 37

Modified XSL<xsl:stylesheet

xmlns:xsl='http://www.w3.org/1999/XSL/Transform' >

<xsl:template match="/"> <H2><xsl:value-of

select="//author"/></H2> <H1><xsl:value-of select="//title"/></H1> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 38

Interesting Tricks – 1 XML (trick-1.xml)

<?xml version="1.0"?><?xml-stylesheet href=“trick-1.xsl" type="text/xsl"?><xslTutorial> <title>XSL</title> <author>John Smith</author> </xslTutorial>

XSL (trick-1.xsl)<?xml version="1.0" ?><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

version="1.0"></xsl:stylesheet>

What would be the output?

XSL | Atul Kahate 39

Answer The full XML contents Why?

If no template is specified, XSLT produces the complete XML as output!

XSL | Atul Kahate 40

Interesting Tricks – 2 XML (trick-2.xml)

<?xml version="1.0"?><?xml-stylesheet href=“trick-2.xsl" type="text/xsl"?><xslTutorial> <title>XSL</title> <author>John Smith</author> </xslTutorial>

XSL (trick-2.xsl)<?xml version="1.0" ?><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

version="1.0"><xsl:template match=“/”>

</xsl:template></xsl:stylesheet>

What would be the output?

XSL | Atul Kahate 41

Answer Now we have said, match root, but

once root is matched, we say do nothing (since there is nothing between <xsl:template match = “/” and </xsl:template> tags

Hence, output is empty

XSL | Atul Kahate 42

Interesting Tricks – 3 XML (trick-3.xml)

<?xml version="1.0"?><?xml-stylesheet href=“trick-3.xsl" type="text/xsl"?><xslTutorial> <title>XSL</title> <author>John Smith</author> </xslTutorial>

XSL (trick-3.xsl)<?xml version="1.0" ?><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

version="1.0"><xsl:template match=“/”>

<xsl:value-of select = “title” /> </xsl:template></xsl:stylesheet>

What would be the output?

XSL | Atul Kahate 43

Answer Now, we try to find a match on the

title element inside /. But the path for title should be

/xslTutorial/title Hence, output would be empty

XSL | Atul Kahate 44

Interesting Tricks – 4 XML (trick-4.xml)

<?xml version="1.0"?><?xml-stylesheet href=“trick-4.xsl" type="text/xsl"?><xslTutorial> <title>XSL</title> <author>John Smith</author> </xslTutorial>

XSL (trick-4.xsl)<?xml version="1.0" ?><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

version="1.0"><xsl:template match=“/”>

<xsl:value-of select = “/xslTutorial/title” /> </xsl:template></xsl:stylesheet>

What would be the output?

XSL | Atul Kahate 45

Answer It would produce the contents of

the title element, as expected, now

Template Basics

XSL | Atul Kahate 47

Usage of Templates <xsl:template match = “…”>

We know that this clause is used to match a particular tag from an XML file and to do processing, accordingly

<xsl:template name = “…”> Allows us to define a template Once such a template is defined, we

can use <xsl:call-template name = “…”> to call that defined template

XSL | Atul Kahate 48

Understanding <apply-templates> class.xml

<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="class.xsl"?> <class> <student>Jack</student> <student>Harry</student> <student>Rebecca</student> <teacher>Mr. Bean</teacher> </class>

Class.xsl<?xml version="1.0" ?> <xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match=“student"> Found a learner! </xsl:template> </xsl:stylesheet>

OutputFound a learner! Found a learner! Found a learner! Mr. Bean

XSL | Atul Kahate 49

How it Works?<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="class.xsl"?> <class> <student>Jack</student> <student>Harry</student> <student>Rebecca</student> <teacher>Mr. Bean</teacher> </class>

<?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="student"> Found a learner! </xsl:template> </xsl:stylesheet>

Step 1: For all matching student tags, display output Found a learner!

Step 2: Come here and run the template recursively for all the student tags, displaying Found a learner!

Step 3: For all tags other than student, there is no template in our XSL. Therefore, blindly output them, as they are!

XSL | Atul Kahate 50

Plain English Version For all the elements in the given

XML If the current element = “student”

Display “Found a learner” Else

Display the actual contents of the element End-if

End-For

XSL | Atul Kahate 51

Explanation The way this works is:

Use a template if one defined Blindly output the contents of the elements

wherever there is no template defined For each <template match = “student”>,

we display the text Found a learner! instead of the student name itself.

However, for the teacher tag, there is no <template match>. Therefore, its contents are displayed as they are.

XSL | Atul Kahate 52

Notes on the Result – 1 Note that we would see display for all the

student tags However, in the first example, we would

have seen the output only for the first instance of title and author tags

Why? In the earlier example, there was no template,

i.e. no recursion – the syntax used was value-of select

Now, we use a template, which introduces recursion

XSL | Atul Kahate 53

Notes on the Result – 2 This style of coding is ambiguous! It can lead to completely

unexpected results Let us modify our XML and XSL

now

XSL | Atul Kahate 54

Modified XML and XSL class1.xml<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="class1.xsl"?> <class> <dept>Bye</dept><salary>10000</salary>

</class> class1.xsl<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="hello"> Found a learner! </xsl:template></xsl:stylesheet>

What would be the output?

XSL | Atul Kahate 55

Output Bye10000

Why? The attempt is to find a match for the tag or

element hello in our XML document, which is not found

For other tags in the XML document (i.e. dept and salary), there is no template defined; so no special processing is needed for them, except blindly outputting their contents, as before!

XSL | Atul Kahate 56

Further Modifications Modified XML<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="class1.xsl"?> <class> <dept>Bye</dept><salary>10000</salary><name><first>test</first><last>test</last></name></class> Resulting OutputBye10000testtest

This is based on same logic as earlier

XSL | Atul Kahate 57

Still More Changes class3.xml<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="class1.xsl"?> <class> <dept>Bye</dept>

<salary>10000</salary></class> class3.xsl<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="dept">Found a learner!</xsl:template><xsl:template match="salary"></xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 58

Output Found a learner!

This is because we have suppressed the output for the salary tag now

Introducing apply-templates

XSL | Atul Kahate 60

Use of <apply-templates> - Tricky class2.xml<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl"

href="class2.xsl"?> <class> <college>test</college>

<dept>one</dept> <salary>10000</salary>

<dept>two</dept> <salary>20000</salary>

<dept>three</dept> <salary>30000</salary></class>

Class2.xsl<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match=“dept"> <xsl:apply-templates /> </xsl:template></xsl:stylesheet>

XSL | Atul Kahate 61

Output Testone10000two20000three3000

0

Reason: The logic works as: If there is at least one dept tag

<apply-templates> (which means, display the default output as it is, which means everything)

XSL | Atul Kahate 62

Suppressing Unwanted Output Modified XSL<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="dept"><xsl:apply-templates/></xsl:template><xsl:template match="salary">

</xsl:template>

</xsl:stylesheet>

Controlling the Output the Way We Want

XSL | Atul Kahate 64

XSL Changed – 1 Now changes the XSL to this:<?xml version="1.0" ?> <xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="class"> <xsl:apply-templates select="student"/> </xsl:template> <xsl:template match="student"> Found a learner! </xsl:template>

</xsl:stylesheet> What would be the output? See next slide.

XSL | Atul Kahate 65

Plain English Version For each element in the given XML

If the current element is class If the child element of the current element is student

Output Found a learner End-if

End-if End-for

Note: There is no Else now!

XSL | Atul Kahate 66

Output of the second XSL Found a learner! Found a learner! Found a learner!

Explanation <xsl:template match="class">

The XSLT processor begins at the root element when looking for template matches. It finds a match for the root element class.

<xsl:apply-templates select="student"/> In our template that matched class we use xsl:apply-templates which will

check for template matches on all the children of class. The children of class in our XML document are student and teacher.

To have the teacher element "Mr. Bean" ignored, we use the select attribute of xsl:apply-templates to specify only student children.

The XSLT processor then goes searching templates that only match student elements.

<xsl:template match="student“> The processor finds the only other template in our XSLT, which prints out

"Found a learner!" for each student element in the XML document. XSLT finds three students, so "Found a learner!" is displayed three times.

XSLT then finishes its processing and we are left with XSLT output that has eliminated the unwanted text, "Mr. Bean!"

XSL | Atul Kahate 67

Beware of this Problem! Suppose the XSL was like this:<?xml version="1.0" ?> <xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="class"> <xsl:apply-templates /> </xsl:template> <xsl:template match="student"> Found a learner! </xsl:template>

</xsl:stylesheet> What would be the output? See next slide.

XSL | Atul Kahate 68

Analysis The only change we have made is

to remove the select attribute from apply-templates

This would translate to something different!

See next slide

XSL | Atul Kahate 69

Plain English Version For each element in the given XML

If the current element is class If the child element of the current element is student

Output Found a learner Else

Output the contents of the current element as they are End-if

End-if End-for

Note: There is an Else now!

XSL | Atul Kahate 70

What about this? XML <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="class.xsl"?> <college> <class> <institution>SICSR</institution> <student>Jack</student> <student>Harry</student> <student>Rebecca</student> <teacher>Mr. Bean</teacher> </class> </college> XSL <?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="class"> <xsl:apply-templates/> </xsl:template> <xsl:template match="student"> Found a learner! </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 71

Output SICSR Found a learner! Found a learner!

Found a learner! Mr. Bean

Explanation The same logic as earlier applies If a match is found, do something; else

display contents of current element blindly Remember, we do not have a select

attribute in the template If we have it, what would happen?

XSL | Atul Kahate 72

Another Variation XML <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="class.xsl"?> <college> <class> <institution>SICSR</institution> <student>Jack</student> <student>Harry</student> <student>Rebecca</student> <teacher>Mr. Bean</teacher> </class> </college>

XSL <?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="class"> <xsl:apply-templates select="student"/> </xsl:template> <xsl:template match="student"> Found a learner! </xsl:template> </xsl:stylesheet>

Output Found a learner! Found a learner! Found a learner!

XSL | Atul Kahate 73

Summary Do not leave our code in an ambiguous

state This happens if we specify <apply-

templates> without any specific select attribute

It can also happen if we do not specify exact selection criteria inside <template match>

Output may not be as expected!

XSL | Atul Kahate 74

Another XSLT Example – 1 Consider the following XML

document<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="pune.xsl"?>

<content><about> PUNE </about><city>

<line1> Pune is a lovely city </line1><line2> The education facilities are as best as you can get </line2><line3> And the weather is great, too. </line3>

</city></content>

XSL | Atul Kahate 75

Another XSLT Example – 2 Here is the corresponding XSLT document<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="content"><html>

<head><title>Welcome to Pune!</title></head><body>

<h1><xsl:value-of select="about"/></h1><h2><xsl:value-of select="city/line1"/></h2><h3><xsl:value-of select="city/line2"/></h3><h4><xsl:value-of select="city/line3"/></h4>

</body></html>

</xsl:template></xsl:stylesheet>

Using Parameters in Templates

XSL | Atul Kahate 77

Using Parameters in Templates<xsl:template name = "print" > <xsl:param name = "A" /> <xsl:param name = "B" >111</xsl:param> <xsl:value-of select = "$A" /> <xsl:text > + </xsl:text> <xsl:value-of select = "$B" /> <xsl:text > = </xsl:text> <xsl:value-of select = "$A+$B" /> </xsl:template> This defines a template (like a method) called as print This template can receive two parameters, named A and B. B has a

default value of 111. The template prints the following as the output:

Value of A + Value of B = Sum of A and BFor example, if a caller calls this template with A = 10 and B = 20, the output will be:10 + 20 = 30

XSL | Atul Kahate 78

Calling Templates<xsl:template match = "/" >

<xsl:call-template name = "print" > <xsl:with-param name = "A" >11</xsl:with-param> <xsl:with-param name = "B" >33</xsl:with-param> </xsl:call-template> <xsl:call-template name = "print" > <xsl:with-param name = "A" >55</xsl:with-param> </xsl:call-template>

</xsl:template>

Now, we are calling the template defined earlier (print) twice in succession: first time passing A = 11 and B = 33; and second time passing A = 55 and not passing any value for B

Output (Full code on next slide): 11 + 33 = 4455 + 111 = 166Note: 111 was B’s default value in the print template on the previous slide

XSL | Atul Kahate 79

Code XML

<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="1.xsl" ?><AAA > <BBB>bbb </BBB> <CCC>ccc </CCC> </AAA>

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

<xsl:template match = "/" > <xsl:call-template name = "print" > <xsl:with-param name = "A" >11</xsl:with-param> <xsl:with-param name = "B" >33</xsl:with-param> </xsl:call-template> <xsl:call-template name = "print" > <xsl:with-param name = "A" >55</xsl:with-param> </xsl:call-template> </xsl:template>

<xsl:template name = "print" > <xsl:param name = "A" /> <xsl:param name = "B" >111</xsl:param> <xsl:text > </xsl:text> <xsl:value-of select = "$A" /> <xsl:text > + </xsl:text> <xsl:value-of select = "$B" /> <xsl:text > = </xsl:text> <xsl:value-of select = "$A+$B" /> </xsl:template> </xsl:stylesheet>

Attributes

XSL | Atul Kahate 81

Dealing with Attributes XML

<?xml version="1.0"?><?xml-stylesheet href="test.xsl" type="text/xsl"?><xslTutorial> <dog name='Joe'> <data weight='18 kg' color="black"/> </dog> </xslTutorial>

XSL<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:template match="dog"> <P><B><xsl:text> Dog: </xsl:text> </B> <xsl:value-of select="@name"/></P> <P><B><xsl:text> Color: </xsl:text> </B> <xsl:value-of select="data/@color"/></P> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 82

Another Example XML <?xml version="1.0"?> <?xml-stylesheet href="products.xsl" type="text/xsl"?>

<card type="simple"> <name>John Doe</name> <title>CEO, Widget Inc.</title> <email>john.doe@widget.com</email> <phone>(202) 456-1414</phone> </card>

XSL <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns="http://www.w3.org/1999/xhtml"> <xsl:template match="card[@type='simple']"> <html xmlns="http://www.w3.org/1999/xhtml"> <title>business card</title><body> <xsl:apply-templates select="name"/> <xsl:apply-templates select="title"/> <xsl:apply-templates select="email"/> <xsl:apply-templates select="phone"/> </body></html> </xsl:template> <xsl:template match="card/name"> <h1><xsl:value-of select="text()"/></h1> </xsl:template> <xsl:template match="email"> <p>email: <a href="mailto:{text()}"><tt> <xsl:value-of select="text()"/> </tt></a></p> </xsl:template>

</xsl:stylesheet>

A Detailed Example

XSL | Atul Kahate 84

discussionForumHome.xml<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet href="discussionForumHome.xsl"

type="text/xsl"?><disussionForumHome> <messageBoard id="1" name="Java Programming"/> <messageBoard id="2" name="XML Programming"/> <messageBoard id="3" name="XSLT

Programming"/></disussionForumHome>

XSL | Atul Kahate 85

discussionForumHome.xsl<?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> <head> <title>Discussion Forum Home Page</title> </head> <body> <h1>Discussion Forum Home Page</h1> <h3>Please select a message board to view:</h3> <ul> <xsl:apply-templates select ="disussionForumHome/messageBoard"/> </ul> </body> </html></xsl:template>

<xsl:template match ="messageBoard"> <li> <a href ="viewForum?id={@id}"> <xsl:value-of select="@name"/> </a> </li> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 86

<xsl:template match = “/”> Read this as: Start processing the

XML document at the root of the document

/ indicates root There are some details

underneath, as explained next

XSL | Atul Kahate 87

Understanding <xsl:template-match> - 1<xsl:template match="/"> <html> <head> <title>Discussion Forum Home Page</title> </head> <body> <h1>Discussion Forum Home Page</h1> <h3>Please select a message board to view:</h3> <ul> <xsl:apply-templates select ="disussionForumHome/messageBoard"/> </ul> </body> </html></xsl:template>

Once root is located, start outputting HTML tags as shown, until the <xsl:apply-templates select ="disussionForumHome/messageBoard"/> is encountered

XSL | Atul Kahate 88

Understanding <xsl:template-match> - 2 <xsl:template match>

Has four optional attributes match – Almost always necessary, takes an

Xpath expression as an argument. When the current node matches the node set defined in this expression, the template is executed.

name – Allows us to refer to the template from elsewhere in the document

priority – NA mode – NA

XSL | Atul Kahate 89

Understanding <xsl:template-match> - 3 But the XSLT also has one more

<xsl:template> element as follows: <xsl:template match ="messageBoard">

Why does this not get the processor’s attention?

This is because by default, only the root is loaded; all other templates must be explicitly called by other parts of the XSLT code, as we shall discuss shortly

XSL | Atul Kahate 90

<xsl:apply-templates> - 1 Tells the XSLT processor to

Begin a new search for elements in the source XML document that match the search pattern

And to look for a matching <xsl:template> element in the XSLT for the same element

Here, we have: <xsl:apply-templates select ="disussionForumHome/messageBoard"/>

Hence, the XSLT processor searches for A pattern disussionForumHome/messageBoard in the XML document A <template-match> element for the same in the

XSLT document

XSL | Atul Kahate 91

<xsl:apply-templates> - 2 The <xsl:apply-templates> element works recursively Here, it tells the XSLT processor to first select the

<discussionForumHome> elements of the current node

Current node here is the root element of the XML document

Hence, it selects all the <discussionForumHome> elements at the root level, which means just one element

However, if we had more elements with the same name deeper in the hierarchy, they would have been ignored

XSL | Atul Kahate 92

<xsl:apply-templates> - 3 Assuming that the XSLT processor locates the

<discussionForumHome> element, it searches for all of its <messageBoard> children

For each <messageBoard> child, the processor looks for the template in our stylesheet that provides the best match

Since our stylesheet contains a template that exactly matches the <messageBoard> pattern, it is instantiated for each of the <messageBoard> elements in the source XML

XSL | Atul Kahate 93

<xsl:template match = “messageBoard”> This template gets invoked for each

instance of the <messageBoard> element <xsl:template match ="messageBoard"> <li> <a href ="viewForum?id={@id}"> <xsl:value-of select="@name"/> </a> </li> </xsl:template>

In each case, it produces a line item, consisting of a hyperlink, displaying the name attribute of the <messageBoard> element, and embedding the id attribute in the URL

XSL | Atul Kahate 94

Summary Most transformation in XSLT is driven by two

elements, <xsl:template> and <xsl:apply-templates>.

Processing begins at root, and then: For each X in the current node, processor searches for all

<xsl:template match = “pattern”> elements in the stylesheet that potentially match the node.

The selected <xsl:template match = “pattern”> is instantiated using node X as its current node. This templates typically copies data from the source XML, or produces brand new content in combination with the source data.

If the template contains <xsl:apply-templates select = “newPattern” />, a new current node is created and the process repeats recursively.

XSL | Atul Kahate 95

Comparing <xsl:template> to <xsl:apply-template> Think about the former as similar

to a Java method definition, and the later as invoking that method

XSL | Atul Kahate 96

Another Example college.xml<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet href="college.xsl" type="text/xsl"?><college> <name>SICSR</name> <city>Pune</city> <state>Maharashtra</state></college>

college.xsl<?xml version="1.0" encoding="utf-8"?>

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

<xsl:template match="college"> <b> <xsl:value-of select ="name"/> is located in <xsl:value-of select ="city"/>, <xsl:value-of select ="state"/>. </b></xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 97

Explanation Elements that do not start with <xsl:>

are simply copied into the result tree <xsl:value of> copies the value of

something in the XML source tree to the result tree

Here, current node is <college>, so <xsl:value-of select = “name”/> selects the text content of the <name> element inside <school>

XSL | Atul Kahate 98

An Example for Conceptual Clarity <customer>

<customer> (Many instance) <name> (Many instances)

<xsl:template match="customers"> <ul> <xsl:apply-templates select ="customer"/> </ul></xsl:template>

<xsl:template match ="customer"> <!– Loops over all customer instances <li> <xsl:value-of select ="name"/> </li></xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 99

Value-of select = ‘.’ XML

<?xml version="1.0"?><?xml-stylesheet href="test.xsl" type="text/xsl"?><xslTutorial> <bold>Hello, world.</bold> <red>I am </red> <italic>fine.</italic> </xslTutorial>

XSL<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:template match="bold"> <P><B><xsl:value-of select="."/></B></P> </xsl:template> <xsl:template match="red"> <P style="color:red"><xsl:value-of select="."/></P> </xsl:template> <xsl:template match="italic"> <P><i><xsl:value-of select="."/></i></P> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 100

Another Example – Can be Confusing! What would be the output? XML

<?xml version="1.0"?><?xml-stylesheet href="test.xsl" type="text/xsl"?><xslTutorial> <employee> <firstName>Joe</firstName> <surName>Smith</surName> </employee> </xslTutorial>

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

<xsl:template match="employee"> <B><xsl:value-of select="."/></B> </xsl:template> <xsl:template match="surName"> <i><xsl:value-of select="."/></i> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 101

Explanation XSLT tries to process the first match (at the

outermost possible level), i.e. on xslTutorial – There is none

So, it tries to find a match on the next level, which is employee; and executes code inside

Now, anything inside the employee tag has to be processed while inside the employee template itself

But surName is outside of employee, and hence will be ignored

XSL | Atul Kahate 102

Modified Example Is this correct now?

XML <?xml version="1.0"?> <?xml-stylesheet href="employee.xsl" type="text/xsl"?> <xslTutorial> <employee> <firstName>Joe</firstName> <middleName>Angus</middleName> <surName>Smith</surName> </employee> </xslTutorial>

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

<xsl:template match="/xslTutorial/employee"> <B><xsl:value-of select="."/></B> <xsl:template match="surName"> <i><xsl:value-of select="."/></i> </xsl:template> </xsl:template> <xsl:template match="/xslTutorial/employee/middleName"> <xsl:value-of select="middleName"/> </xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 103

Analysis No! Inside an <xsl:template-match>,

another <xsl:template match> cannot exist

How to print the last name, then?

XSL | Atul Kahate 104

Modified Example XML

<?xml version="1.0"?> <?xml-stylesheet href="employee.xsl" type="text/xsl"?> <xslTutorial> <employee> <firstName>Joe</firstName> <middleName>Angus</middleName> <surName>Smith</surName> </employee> </xslTutorial>

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

<xsl:template match="/xslTutorial/employee"> <B><xsl:value-of select="."/></B> <xsl:apply-templates /> </xsl:template>

<xsl:template match="/xslTutorial/employee/surName"> <xsl:value-of select=“."/> </xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 105

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

<xsl:template match="/xslTutorial/employee"> <B><xsl:value-of select="."/></B> <xsl:apply-templates /> </xsl:template>

<xsl:template match="/xslTutorial/employee/firstName"> <h1> <xsl:value-of select="."/> </h1> </xsl:template>

<xsl:template match="/xslTutorial/employee/middleName"> <i> <xsl:value-of select="."/> </i> </xsl:template>

<xsl:template match="/xslTutorial/employee/surName"> <h2> <xsl:value-of select="."/> </h2> </xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 106

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

<xsl:template match="/xslTutorial/employee"> <B><xsl:value-of select="."/></B> <xsl:apply-templates /> </xsl:template>

<xsl:template match="/xslTutorial/employee/firstName"> <h1> <xsl:value-of select="."/> </h1> </xsl:template>

<!-- <xsl:template match="/xslTutorial/employee/middleName"> <i> <xsl:value-of select="."/> </i> </xsl:template> -->

<xsl:template match="/xslTutorial/employee/surName"> <h2> <xsl:value-of select="."/> </h2> </xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 107

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

<xsl:template match="/xslTutorial/employee"> <B><xsl:value-of select="."/></B> <xsl:apply-templates /> </xsl:template>

<!--

<xsl:template match="/xslTutorial/employee/firstName"> <h1> <xsl:value-of select="."/> </h1> </xsl:template>

<xsl:template match="/xslTutorial/employee/middleName"> <i> <xsl:value-of select="."/> </i> </xsl:template>

<xsl:template match="/xslTutorial/employee/surName"> <h2> <xsl:value-of select="."/> </h2> </xsl:template> -->

</xsl:stylesheet>

XSL | Atul Kahate 108

Yet Another Version – Only middle name would get displayed after the complete name <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version="1.0">

<xsl:template match="/xslTutorial/employee"> <B><xsl:value-of select="."/></B> <xsl:apply-templates select=“middleName”/> </xsl:template>

<xsl:template match="/xslTutorial/employee/middleName"> <i> <xsl:value-of select="."/> </i> </xsl:template>

<xsl:template match="/xslTutorial/employee/surName"> <h2> <xsl:value-of select="."/> </h2> </xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 109

Controlling the Output Method Try adding

<xsl:output method=“html” /> <xsl:output method=“xml” /> <xsl:output method=“text” />

one after the other Run the example from the command prompt

as: set CLASSPATH=c:\xalan\bin\xalan.jar java org.apache.xalan.xslt.Process -INDENT 3 -IN

employee.xml -XSL employee.xsl -OUT output.html

More XSLT Examples

XSL | Atul Kahate 111

First XSL Example: Hello World! XML Document (HelloWorld.xml)

<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="HelloWorld.xsl" type="text/xsl"?><msg>Hello World!</msg>

XSL Document (HelloWorld.xsl)<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="text"/><xsl:template match="msg">Found it!</xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 112

Second XSL example XML Document (second.xml)

<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="second.xsl" type="text/xsl"?><message>We can easily output XML using XSLT!</message>

XSL Document (second.xsl)<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="text"/><xsl:template match="/">Message in XML document is: <xsl:apply-templates/>!</xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 113

Third XSL Example XML document (third.xml)

<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="third.xsl" type="text/xsl"?><name>

<first>Sachin</first><last> Tendukar</last>

</name> XSL document (third.xsl)

<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="name"><html>

<head><title>XSL Output Example</title>

</head><body>

<p><xsl:apply-templates select="first"/>

</p><p>

<xsl:apply-templates select="last"/></p>

</body></html>

</xsl:template></xsl:stylesheet>

XPath Basics

XSL | Atul Kahate 115

Nodes XPath views a document as a tree This tree consists of nodes One node can contain other child

nodes There are 7 types of nodes

root, element, attribute, text, comment, processing instruction, and namespace

XSL | Atul Kahate 116

Sample XML Document<?xml version = “1.0”?><!-- This is a comment --><BOOK author = “Andrew Tanenbaum” edition =

“3”><REVIEW> This is a wonderful book!</REVIEW>

Computer Networks</BOOK>

XSL | Atul Kahate 117

XPath ViewRoot

CommentThis is a comment

ElementBOOK

Attributeauthor

Andrew Tanenbaum

Attributeedition

3

ElementREVIEW

TextThis is a wonderful book!

TextComputer Networks

XSL | Atul Kahate 118

XPath Basics XPath allows selection of

nodes/attributes based on certain conditions

XSLT processes these nodes XPath expressions

Criteria for selection of nodes/attributes Location path

Similar to street directions: Used for locating information in an XML document

XSL | Atul Kahate 119

XPath Example child::chapter[child::title]

Look for child nodes of the current node (called as the context node) representing the <chapter> element

Within that, look only for child nodes that represent the <title> element

<chapter><title>

XSL | Atul Kahate 120

XPath Examples – 1Syntax Meaning Examplechild::paragra

phSelect the

<paragraph> child element nodes of the context node.

If context is book, empty node-set would be returned. If context node is <section> element in chapter 2 with attribute number =“1”, a node-set containing four paragraph nodes would be returned.

child::* Select all element node children of the context node. Children other than the element node are not selected.

If context node is the <book> element, the node-set containing <title>, <chapters> and <appendices> nodes would be returned.

child::text() Select all text node children of the context node.

If context node is the <book> element, an empty node-set would be returned. If the context node is <paragraph> number 1 in <section> 2 of <chapter> 2, the returned node-set would be the text node with value First paragraph.

XSL | Atul Kahate 121

XPath Examples – 2Syntax Meaning Example

child::node() Select all the child nodes of the context node. Note that this will return non-elements also.

NA

attribute::number

Select all attribute nodes with name number under the context node.

NA

attribute::* Select all attribute nodes of the context node.

If context node is the <chapter> 1 element, a node-set containing two attribute nodes would be returned, representing the number and title attributes.

XSL | Atul Kahate 122

XPath Examples – 3Syntax Meaning Exampledescendant::p

aragraphSelect all <paragraph>

elements that are descendants of the context node.

If the context node is <book> or <chapters> element, we would get a node-set consisting of six <paragraph> nodes.

If the context node is <section> 1 element for <chapter> 2, we would get a node-set consisting of four <paragraph> nodes.

ancestor-or-self::chapter

Select the <chapter> element nodes that are ancestors of the context node. If the context node is a <chapter> element, return that also.

If the context node is <chapters>, an empty node-set would be returned. If the context node is a <section>, the result would be a node-set containing one <chapter> element which contains this <section> element.

self:paragraph Select the context node if it is the <paragraph> element.

NA

XSL | Atul Kahate 123

attribute::reviewer @reviewer Attribute reviewer of the context node.

attribute::* @* All attributes of the context node.

parent::node ()/attribute::reviewer ..@reviewer Attribute reviewer of the parent of the context node.

child::AUTHOR [position () = 1] AUTHOR [1] First AUTHOR child node of the context node.

child::AUTHOR [position () = last ()]

AUTHOR [last ()] Last AUTHOR child node of the context node.

child::REVIEW [attribute::reviewer = “Jui”]

REVIEW [@reviewer = “Jui”] All REVIEW element children of the context node having a reviewer attribute with a value of Jui.

child::REVIEW [attribute::reviewer = “Jui’] [2]

REVIEW [@reviewer = “Jui”] [2] Second REVIEW child of

the context node having a reviewer attribute with a value of Jui.

XSL | Atul Kahate 124

Template Rules Describes how an XML element node is

converted into an XSL element node for displaying

Examples<xsl: template match=“/article/title”><xsl: template match=“line”><xsl: template match=“city/line”><xsl: template match=“content//line”><xsl: template match=“title | line”><xsl:template match=“/article/*”<xsl:template match=“/article/section[2]/title/text()”

XSL | Atul Kahate 125

<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

The value of the required select attribute contains an XPath expression

It works like navigating a file system where a forward slash (/) selects subdirectories

XSL | Atul Kahate 126

XSLT Example Consider the following XML document<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="history.xsl"?><subject>

<info>History of India</info></subject> We can write the following XSLT code to transform this into

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

<xsl:template match="subject"><html>

<head><title>Hello World</title></head><body>

<h2> <xsl:value-of select="info"/> </h2></body>

</html></xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 127

Exercise Write an XSLT document for the following XML

document to display it as HTML

<?xml version = “1.0” ?><?xml:stylesheet type = “text/xsl” href = “one.xsl”?

><myPerson>

<personName>Sachin Tendulkar</personName></myPerson>

XSL | Atul Kahate 128

Solution<xsl:stylesheet version = “1.0” xmlns:xsl =

“http://www/w3.org/1999/XSL/Transform”><xsl:template match = “myPerson”>

<html><body>

<b> <xsl:value-of select = “personName”/> </b>

</body></html>

</xsl:template></xsl:stylesheet>

XSL | Atul Kahate 129

Exercise Consider the following XML file:

<?xml version=“1.0”?><BOOK>

<BOOK_TITLE>Computer Networks</BOOK_TITLE><AUTHOR>Tanenbaum</AUTHOR>

</BOOK>

Use XSL to display title and author as level 1 and level 2 headers, respectively

XSL | Atul Kahate 130

Solution<xsl:stylesheet version=“1.0”

xmlns:xsl=“http://www.w3.org/1999/XSL/Transform”><xsl:template match=“BOOK”>

<html><head><title> Book Information </title></head><body> <h1><xsl:value-of

select=“BOOK_TITLE”/></h1> <h2>by <xsl:value-of

select=“AUTHOR”/></h2></body>

</html></xsl:template></xsl:stylesheet>

XSL | Atul Kahate 131

Exercise Consider this XML and write an XSL to display only the book title and price

<?xml version = “1.0” ?><?xml version = "1.0" ?><?xml:stylesheet type = "text/xsl" href = "book2.xsl"?>

<CATALOG><BOOK>

<TITLE>Computer Networks</TITLE><AUTHORS>

<AUTHOR>Andrew Tanenbaum</AUTHOR></AUTHORS><PUBYEAR>2003</PUBYEAR><PRICE>250</PRICE>

</BOOK><BOOK>

<TITLE>Computer Fundamentals</TITLE ><AUTHORS>

<AUTHOR>Rajaraman</AUTHOR><AUTHOR>Ghosh</AUTHOR>

</AUTHORS><PUBYEAR>2002</PUBYEAR><PRICE>250</PRICE>

</BOOK></CATALOG>

XSL | Atul Kahate 132

Solution<xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="BOOK">Book Name: <xsl:value-of select="TITLE"/> Price: <xsl:value-of select="PRICE"/></xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 133

Exercise Consider the following XML document, titled emp.xml:<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="emp.xsl"?><EMP_INFO>

<EMPLOYEE><EMP_NAME empID="9662">

<FIRST>Sachin</FIRST><LAST>Tendulkar</LAST>

</EMP_NAME></EMPLOYEE>

</EMP_INFO> Write emp.xsl file mentioned above, which would:

Display a heading Emp Name:, followed by the employee’s name.

Display the employee id below this, in a smaller font.

XSL | Atul Kahate 134

Solution<xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="EMP_INFO"> <html> <head><title>Emp Info!</title></head>

<body> <h1>Emp Name: <xsl:value-of select="EMPLOYEE/EMP_NAME/FIRST"/>

<xsl:value-of select="EMPLOYEE/EMP_NAME/LAST"/> </h1>

<h3> <xsl:value-of select="EMPLOYEE/EMP_NAME/@empID"/></h3> </body>

</html></xsl:template></xsl:stylesheet>

Concept of apply-templates

XSL | Atul Kahate 136

apply-templates We know that <xsl:template

match=“…”> allows us to search for a location path in our XML document

Another XSLT syntax, <xsl:apply-templates/> allows us to list the contents of the elements with reference to the previous <xsl:template match=“…”> declaration

Examples follow

XSL | Atul Kahate 137

Source XML (apply.xml)<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="apply1.xsl"?><book>

<title>Profesional XSL</title><chapters>

<chapter><chapterNo>2</chapterNo><chapterTopic>XPath</chapterTopic><chapterAuthor>Andrew Watt</chapterAuthor><chapterSections><chapterSection>Section 1</chapterSection><chapterSection>Section 2</chapterSection><chapterSection>Section 3</chapterSection><chapterSection>Section 4</chapterSection><chapterSection>Section 5</chapterSection><chapterSection>Section 6</chapterSection></chapterSections></chapter>

<chapter><chapterNo>3</chapterNo><chapterTopic>XSLT Basics</chapterTopic><chapterAuthor>Paul Spencer</chapterAuthor><chapterSections><chapterSection>Section 1</chapterSection><chapterSection>Section 2</chapterSection><chapterSection>Section 3</chapterSection><chapterSection>Section 4</chapterSection><chapterSection>Section 5</chapterSection><chapterSection>Section 6</chapterSection></chapterSections></chapter><chapter><chapterNo>4</chapterNo><chapterTopic>Modular XSLT</chapterTopic><chapterAuthor>Kurt Cagle</chapterAuthor><chapterSections><chapterSection>Section 1</chapterSection><chapterSection>Section 2</chapterSection><chapterSection>Section 3</chapterSection><chapterSection>Section 4</chapterSection><chapterSection>Section 5</chapterSection><chapterSection>Section 6</chapterSection></chapterSections></chapter></chapters>

</book>

XSL | Atul Kahate 138

Basic XSL Example (apply0.xml) <xsl:stylesheet

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

<xsl:template match="/"> </xsl:template>

</xsl:stylesheet> What would be the output?

XSL | Atul Kahate 139

Explanation We have not specified what action

should be taken when root is applied

This causes the entire output to be suppressed!

XSL | Atul Kahate 140

XSL Example: 1 (apply1.xsl)<?xml version="1.0"?><xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/"><xsl:apply-templates/>

</xsl:template>

</xsl:stylesheet>

Output: ?

XSL | Atul Kahate 141

Explanation Now there is an <apply-templates>

inside the <template match> This causes the default <apply-

templates> to be applied, i.e. without any particular select inside <apply-templates>

In other words, <apply-templates> gets executed for all elements inside the root

XSL | Atul Kahate 142

XSL Example: 2 (apply2.xsl)<?xml version="1.0"?><xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/"><xsl:apply-templates/>

</xsl:template>

<xsl:template match="*"></xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 143

Explanation Empty output, since <apply-

templates/> will bring search from the root level to all non-root elements.

But at that level, there is no <apply-templates/> to display anything, unlike in the previous example.

XSL | Atul Kahate 144

XSL Example: 3 (apply3.xsl) <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/"> <xsl:apply-templates/> </xsl:template>

<xsl:template match="*"> </xsl:template>

<xsl:template match="book"> <xsl:apply-templates/> </xsl:template>

<xsl:template match="chapters"> <xsl:apply-templates/> </xsl:template>

<xsl:template match="chapter"> <xsl:apply-templates/> </xsl:template>

<xsl:template match="chapterTopic"> <!-- <xsl:apply-templates/> --> <xsl:value-of select="."/> </xsl:template>

</xsl:stylesheet>

Display the list of chapter topics

XSL | Atul Kahate 145

XSL Example: 4 (apply4.xsl) <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/"> <xsl:apply-templates/> </xsl:template>

<xsl:template match="*"> </xsl:template>

<xsl:template match="book"> <xsl:apply-templates/> </xsl:template>

<xsl:template match="chapters"> <xsl:apply-templates/> </xsl:template>

<xsl:template match="chapter"> <xsl:apply-templates/> </xsl:template>

<xsl:template match="/book/chapters/chapter/chapterNo"> <xsl:value-of select="."/> </xsl:template>

<xsl:template match="/book/chapters/chapter/chapterTopic"> <xsl:value-of select="."/> </xsl:template>

<xsl:template match="/book/chapters/chapter/chapterAuthor"> <xsl:value-of select="."/> </xsl:template>

</xsl:stylesheet>

Display element values for all the selected elements

XSL | Atul Kahate 146

XSL Example: 6 (apply6.xsl) - Tricky<?xml version="1.0"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/

1999/XSL/Transform">

</xsl:stylesheet>

XSL | Atul Kahate 147

XSL Example: 5 (apply5.xsl) – Tricky! What if we remove all search paths except the absolute ones?<?xml version="1.0"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/book/chapters/chapter/chapterNo"><xsl:value-of select="."/>

</xsl:template>

<xsl:template match="/book/chapters/chapter/chapterTopic"><xsl:value-of select="."/>

</xsl:template>

<xsl:template match="/book/chapters/chapter/chapterAuthor"><xsl:value-of select="."/>

</xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 148

Explanation Here, there is no <apply-

templates> calling any of the defined <template match> tags

Hence, our <template match> tags would get ignored completely

Hence, it would produce the full XML contents as the output

Using the Mode Attribute

XSL | Atul Kahate 150

Using Mode If more than one template matches an

identical pattern, a conflict arises This can be solved by using template

priority, but at times, that is also ambiguous

In such situations, we can use the template mode

Useful when a template needs to visit the same node, but with different results

XSL | Atul Kahate 151

Mode Example, also uses CSS

XML (css-example-1) <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="css-example-1.xsl"?> <us> <state name="Hawaii"> <county name="Hawaii"> <city class="largest">Hilo</city> </county> <county name="Honolulu"> <city class="largest">Honolulu</city> </county> <county name="Kauai"> <city class="largest">Kapaa</city> </county> <county name="Maui"> <city class="largest">Kahului</city> </county> </state> </us>

XSL <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html"/> <xsl:template match="us/state"> <html> <head> <title>State: <xsl:value-of select="@name"/> </title> <style type="text/css"> h1, h2 {font-family: sans-serif, color: blue} ul {font-size: 16pt} </style> </head> <body> <h1> State: <xsl:value-of select="@name"/> </h1> <h2>All Countries</h2> <ul> <xsl:apply-templates select="county" mode="county"/> </ul> <h2>Largest Cities (by County)</h2> <ul> <xsl:apply-templates select="county" mode="city"/> </ul> </body> </html> </xsl:template> <xsl:template match="county" mode="county"> <li> <xsl:value-of select="@name"/> </li> </xsl:template> <xsl:template match="county" mode="city"> <li> <xsl:value-of select="city"/> (<xsl:value-of select="@name"/>) </li> </xsl:template> </xsl:stylesheet>

Creating New Elements and Attributes

XSL | Atul Kahate 153

Creating Elements and Attributes<?xml version="1.0"?><students>

<student first_name="Raju"><id>101</id><remarks> A student who is not at all

sincere!</remarks></student><student first_name="Aarati">

<id>102</id><remarks> A student who is really quite dedicated to

her studies!</remarks></student><student first_name="Rajani">

<id>103</id><remarks> A student who is awesome!</remarks>

</student></students>

XSL | Atul Kahate 154

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

<xsl:template match="/"><xsl:apply-templates/>

</xsl:template><xsl:template match="students">

<students><xsl:apply-templates/>

</students></xsl:template><xsl:template match="student">

<xsl:element name="{@first_name}"><xsl:attribute name="id"><xsl:value-of

select="id"/></xsl:attribute><notes>

<xsl:value-of select="remarks"/></notes>

</xsl:element></xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 155

Explanation - 1<xsl:template match="/">

<xsl:apply-templates/></xsl:template> match = “/” means select root <xsl:apply-templates/> means

look for a “xsl:template match” at the root level; i.e. look for a definition that says <xsl:template match=“students">

XSL | Atul Kahate 156

Explanation – 2<xsl:template match="students">

<students><xsl:apply-templates/></students></xsl:template>

When the students element is found, output <students> </students>

Then look for a match inside <students> tag, i.e. for <student> tag now

XSL | Atul Kahate 157

Explanation – 3<xsl:template match="student">

<xsl:element name="{@first_name}"><xsl:attribute name="id"><xsl:value-of select="id"/></xsl:attribute><notes><xsl:value-of select="remarks"/></notes></xsl:element></xsl:template>

When the <student> element is found, create a new element in the output XML whose element name equals the value of the attribute first_name in the input XML

So:<student first_name="Raju">

<id>101</id><remarks> A student who is not at all sincere!</remarks>

</student> Will now become

<Raju> </Raju>

XSL | Atul Kahate 158

Explanation – 4<xsl:attribute name="id">

<xsl:value-of select="id"/></xsl:attribute>

Add an attribute named id to the output XML, which equals the value of the element id of the input XML

XSL | Atul Kahate 159

Explanation – 5<notes>

<xsl:value-of select="remarks"/></notes>

Add a new element called as notes to the output XML, which should contain the value of the remarks element of the input XML

XSL | Atul Kahate 160

Explanation – 6 Input XML

<student first_name="Raju"><id>101</id><remarks> A student who is not at all sincere!</remarks>

</student>

Output XML <Raju id = “101”> <comments> A student who is not at all

sincere!</comments> </Raju>

XSL | Atul Kahate 161

Running the Example set CLASSPATH=C:\xalan\

xalan.jar;C:\xalan.xerces.jar

java org.apache.xalan.xslt.Process -INDENT 3 -IN three.xml -XSL three.xsl -OUT output.xml

XSL | Atul Kahate 162

Xalan and Xerces Xalan: Fully implements XSLT,

XPath, and JAXP Xerces: Implements XML

specifications, namespaces, schema, SAX, DOM, and JAXP

Looping using for-each

XSL | Atul Kahate 164

Example: Change XML Contents into an HTML Table – XML File<?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> <cd> <title>Candle in the wind</title> <artist>Elton John</artist> <country>UK</country> <company>HMV</company> <price>8.20</price> <year>1998</year> </cd></catalog>

XSL | Atul Kahate 165

Example: Change XML Contents into an HTML Table – 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 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>

XSL | Atul Kahate 166

Exercise Display name, address, and phone number for all customers in a table <?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="foreach.xsl" ?><customers>

<customer><name>Mahesh Katare</name><address>Eve's Plaza, Bangalore</address><state>Karnataka</state><phone>(80) 3247890</phone></customer><customer><name>Naren Limaye</name><address>Shanti Apartments, Thane</address><state>Maharashtra</state><phone>(22) 82791810</phone></customer><customer><name>Uday Bhalerao</name><address>Kothrud, Pune</address><state>Maharashtra</state><phone>(20) 25530834</phone></customer><customer><name>Amol Kavthekar</name><address>Station Road, Solapur</address><state>Maharashtra</state><phone>(217) 2729345</phone></customer><customer><name>Meghraj Mane</name><address>Cannuaght Place, Delhi</address><state>Delhi</state><phone>(11) 57814091</phone></customer><customer><name>Sameer Joshi</name><address>Gullapetti, Hyderabad</address><state>Andhra Pradesh</state><phone>93717-90911</phone></customer>

</customers>

XSL | Atul Kahate 167

Solution<?xml version="1.0"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <xsl:template match="/"> <HTML> <BODY> <TABLE border = "2"> <xsl:for-each select="customers/customer"> <TR> <TD><xsl:value-of select="name" /></TD> <TD><xsl:value-of select="address" /></TD> <TD><xsl:value-of select="phone" /></TD> </TR> </xsl:for-each> </TABLE> </BODY> </HTML> </xsl:template>

XSL | Atul Kahate 168

Exercise Achieve the same results without

using for-each

XSL | Atul Kahate 169

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

<xsl:template match="/"><HTML>

<BODY><TABLE border="2">

<xsl:apply-templates/></TABLE>

</BODY></HTML>

</xsl:template><xsl:template match="customers/customer">

<TR><TD>

<xsl:value-of select="name"/></TD><TD>

<xsl:value-of select="address"/></TD><TD>

<xsl:value-of select="phone"/></TD>

</TR></xsl:template>

</xsl:stylesheet>

Another for-each Example

XSL | Atul Kahate 171

Exercise: XML<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="SalesToHTML.xsl"

type="text/xsl"?><SalesReport>

<Company>i-flex Solutions Limited</Company><Period>2005-06</Period><Sales Region="US">USD 250 Million</Sales><Sales Region="Europe">USD 100 Million</Sales><Sales Region="Asia">USD 50 Million</Sales>

</SalesReport>

XSL | Atul Kahate 172

Solution: XSL <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html"/> <xsl:template match="/"> <html> <head> <title>Sales Report, <xsl:value-of select="/SalesReport/Company"/>: <xsl:value-of select="/SalesReport/Period"/> </title> </head> <body> <br/> <h2> <xsl:value-of select="/SalesReport/Company"/>, Sales Report: <xsl:value-of select="/SalesReport/Period"/> </h2> <br/> <table width="50%"> <tr> <th>Region</th> <th>Sales</th> </tr> <xsl:for-each select="/SalesReport/Sales"> <tr> <td align="center"> <xsl:value-of select="@Region"/> </td> <td align="center"> <xsl:value-of select="."/> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

Sorting Data

XSL | Atul Kahate 174

Sorting XML

<?xml version="1.0"?><?xml-stylesheet href="test.xsl" type="text/xsl"?><xslTutorial> <name>John</name> <name>Josua</name> <name>Charles</name> <name>Alice</name> <name>Martha</name> <name>George</name> </xslTutorial>

XSL<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version="1.0"> <xsl:template match="/"> <TABLE> <xsl:for-each select="//name"> <xsl:sort order="ascending" select="."/> <TR><TH><xsl:value-of select="."/></TH></TR> </xsl:for-each> </TABLE> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 175

Sorting Information<?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>

XSL | Atul Kahate 176

Sorting – Another Example – XML File

<?xml version="1.0" ?>

<famous-persons>

<persons category="medicine"> <person> <firstname> Edward </firstname> <name> Jenner </name> </person>

<person> <firstname> Gertrude </firstname> <name> Elion </name> </person> </persons>

<persons category="computer science"> <person> <firstname> Charles </firstname> <name> Babbage </name> </person>

<person> <firstname> Alan </firstname> <name> Touring </name> </person>

<person> <firstname> Ada </firstname> <name> Byron </name> </person> </persons>

<persons category="astronomy"> <person> <firstname> Tycho </firstname> <name> Brahe </name> </person>

<person> <firstname> Johannes </firstname> <name> Kepler </name> </person>

<person> <firstname> Galileo </firstname> <name> Galilei </name> </person> </persons>

</famous-persons>

XSL | Atul Kahate 177

Sorting – Another Example – XSLT Write an XSLT for sorting data

appropriately

XSL | Atul Kahate 178

Sorting and Data Types – 1 XML

<?xml version="1.0"?><?xml-stylesheet href="test.xsl" type="text/xsl"?><xslTutorial > <car id="11"/> <car id="6"/> <car id="105"/> <car id="28"/> <car id="9"/> </xslTutorial>

XSL<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version="1.0"> <xsl:template match="/"> <TABLE> <xsl:for-each select="//car"> <xsl:sort data-type="text" select="@id"/> <TR><TH><xsl:text> Car-</xsl:text> <xsl:value-of select="@id"/></TH></TR> </xsl:for-each> </TABLE> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 179

Sorting and Data Types – 2 Modified XSL

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

<xsl:template match="/"> <TABLE> <xsl:for-each select="//car"> <xsl:sort data-type=“number" select="@id"/> <TR><TH><xsl:text> Car-</xsl:text> <xsl:value-of select="@id"/></TH></TR> </xsl:for-each> </TABLE> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 180

Sorting on Multiple Keys Specify multiple xsl:sort elements,

one after the other Example

<xsl:sort select=“SURNAME”/><xsl:sort select=“FIRSTNAME”/><xsl:sort select=“BIRTH_DATE”

order=“ascending”/>

XSL | Atul Kahate 181

Another Sort Example sort-1.xml <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="sort-1.xsl"?> <europe> <state>Belgium</state> <state>Germany</state> <state>United Kingdom</state> <state>France</state> <state>Spain</state> <state>Italy</state> <state>Turkey</state> <state>Sweden</state> <state>Ireland</state> <state>Greece</state> <state>Malta</state> <state>Vatican City</state> <state>Portugal</state> </europe>

sort-1.xsl <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="europe"> <xsl:text>Alphabetical List of European States</xsl:text> <xsl:text>&#10;Total Number of States: </xsl:text> <xsl:value-of select="count(state)"/> <xsl:text>&#10;&#10;</xsl:text> <xsl:apply-templates select="state"> <xsl:sort/> </xsl:apply-templates> </xsl:template> <xsl:template match="state"> <xsl:text> - </xsl:text> <xsl:apply-templates/> <xsl:text>&#10;</xsl:text> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 182

Producing HTML Output <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html"/> <xsl:template match="europe"> <html> <head> <title>European States</title> </head> <style type="text/css">body {font-family: sans-serif}</style> <body> <h3>Alphabetical List of European States</h3> <p> <b>Total Number of States:</b> <xsl:value-of select="count(state)"/> </p> <ul> <xsl:apply-templates select="state"> <xsl:sort/> </xsl:apply-templates> </ul> </body> </html> </xsl:template> <xsl:template match="state"> <li> <xsl:apply-templates/> </li> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 183

Sorting on Attributes and Formatting <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="europe"> <xsl:text>Number of EU Member States: </xsl:text> <xsl:value-of select="count(state)"/> <xsl:text>&#10;</xsl:text> <xsl:apply-templates select="state/@joined"> <xsl:sort data-type="number"/> </xsl:apply-templates> <xsl:text>&#10;</xsl:text> </xsl:template> <xsl:template match="state/@joined"> <xsl:text> - </xsl:text> <xsl:apply-templates select=".."/> <xsl:text> (</xsl:text> <xsl:value-of select="."/> <xsl:text>)&#10;</xsl:text> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 184

Another Sort Example for Multiple Fields

item-list.xml <?xml version="1.0" encoding="UTF-8"?> <list> <freezer> <item>peas</item> <item>green beans</item> <item>pot pie</item> <item>ice cream</item> </freezer> <bakery> <item>rolls</item> <item>jelly doughnuts</item> <item>bread</item> </bakery> <produce> <item>tomato</item> <item>apple</item> <item>potato</item> </produce> </list>

item-list.xsl <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="list"> <xsl:apply-templates select="*"> <xsl:sort select="name()"/> </xsl:apply-templates> </xsl:template> <xsl:template match="*"> <xsl:text>Section: </xsl:text> <xsl:value-of select="name()"/> <xsl:text>&#10;</xsl:text> <xsl:apply-templates select="item"> <xsl:sort/> </xsl:apply-templates> </xsl:template> <xsl:template match="item"> <xsl:text> * </xsl:text> <xsl:apply-templates/> <xsl:text>&#10;</xsl:text> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 185

Explanation The first template matches the list element

and sorts on the names (using name ()) of the element children (using *) of the list This is the first sort

The second template matches only on the element children of list, again using * After inserting some text (such as Section:), and

the name of the element (again using name()), the template sorts the text node content of item children

This is the second sort

Conditional Processing

XSL | Atul Kahate 187

Writing Conditions Using <xsl:if><?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>

XSL | Atul Kahate 188

<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

Example follows

XSL | Atul Kahate 189

Exercise Consider the following XML document<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="books3.xsl"?>

<BOOKS><BOOK pubyear="1929">

<BOOK_TITLE>Look Homeward, Angel</BOOK_TITLE><AUTHOR>Wolfe, Thomas</AUTHOR>

</BOOK><BOOK pubyear="1973">

<BOOK_TITLE>Gravity's Rainbow</BOOK_TITLE><AUTHOR>Pynchon, Thomas</AUTHOR>

</BOOK><BOOK pubyear="1977">

<BOOK_TITLE>Cards as Weapons</BOOK_TITLE><AUTHOR>Jay, Ricky</AUTHOR>

</BOOK><BOOK pubyear="2001">

<BOOK_TITLE>Computer Networks</BOOK_TITLE><AUTHOR>Tanenbaum, Andrew</AUTHOR>

</BOOK></BOOKS> Do the following:

1. Display all the books published in the 1970s.2. Display the same information in a tabular form with an asterisk against the book title.3. Display the same information as in (2), sorted on author name.

XSL | Atul Kahate 190

Solution Refer to books.xml, books.xsl,

books2.xsl, books3.xsl

XSL | Atul Kahate 191

Understanding position () and number

XML (functions-example-1) <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="functions-example-1.xsl"?> <europe> <state>Belgium</state> <state>Germany</state> <state>United Kingdom</state> <state>France</state> <state>Spain</state> <state>Italy</state> <state>Turkey</state> <state>Sweden</state> <state>Ireland</state> <state>Greece</state> <state>Malta</state> <state>Vatican City</state> <state>Portugal</state> </europe>

XSL

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="/"> <table border="2"> <tbody> <tr> <th>Title</th> <th>Position</th> <th>Number</th> </tr> <xsl:apply-templates select="europe/state"/> </tbody> </table> </xsl:template> <xsl:template match="europe/state"> <tr> <td> <xsl:value-of select="."/> </td> <td align="center"> <xsl:value-of select="position()"/> </td> <td align="center"> <xsl:number/> </td> </tr> </xsl:template> </xsl:stylesheet>

Writing Conditions

XSL | Atul Kahate 193

if Example – 1 Consider an XML file (names.xml) as follows. Display all the names

comma-separated in the output HTML file.

<?xml version='1.0'?><?xml-stylesheet type="text/xsl" href="ifcomma2.xsl" ?><namelist> <name>Albert</name> <name>Terrance</name> <name>Will</name> <name>Sylvia</name> <name>Timothy</name> <name>Gordon</name> <name>James</name> <name>Robert</name> <name>Dan</name> <name>Sasha</name></namelist>

XSL | Atul Kahate 194

if Example – 1<?xml version='1.0'?><xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

<xsl:template match="namelist/name"> <xsl:apply-templates/> <xsl:if test="position()!=last()">, </xsl:if></xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 195

if Example – 2 Another way to achieve the same objective

<?xml version='1.0'?><xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

<xsl:template match="namelist/name"> <xsl:if test="position()!=1">, </xsl:if> <xsl:apply-templates/></xsl:template></xsl:stylesheet>

XSL | Atul Kahate 196

if Example – 3 Consider the following XML file (items.xml) and display alternate rows

in yellow background.<?xml version='1.0'?><?xml-stylesheet type="text/xsl" href="ifyellow.xsl" ?><items> <item>Car</item> <item>Pen</item> <item>LP Record</item> <item>Wisdom</item> <item>Cell phone</item> <item>Film projector</item> <item>Hole</item> <item>Canopy</item> <item>Widget</item> <item>Concept</item> <item>Null character</item></items>

XSL | Atul Kahate 197

if Example – 3<?xml version='1.0'?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

<xsl:template match="/"><html><body><table border="1" cellpadding="2" cellspacing="0" width="50%"><xsl:apply-templates/></table></body></html></xsl:template>

<xsl:template match="item"> <tr> <xsl:if test="position() mod 2 = 0"> <xsl:attribute name="bgcolor">yellow</xsl:attribute> </xsl:if> <xsl:apply-templates/> </tr></xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 198

Writing Conditions Using <xsl:choose><?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>

XSL | Atul Kahate 199

choice Example Consider the following XML file (order.xml). If total number of items selected is <10, display

small, if between 10 and 19, display medium, else large.<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="refchoose.xsl" ?><orders> <order> <lineitem/> <lineitem/> <total>9</total> </order> <order> <lineitem/> <lineitem/> <total>19</total> </order> <order> <lineitem/> <lineitem/> <total>29</total> </order></orders>

XSL | Atul Kahate 200

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

<xsl:template match="order"> <xsl:choose> <xsl:when test="total &lt; 10"> (small) </xsl:when> <xsl:when test="total &lt; 20"> (medium) </xsl:when> <xsl:otherwise> (large) </xsl:otherwise> </xsl:choose> <xsl:apply-templates /> <BR/></xsl:template>

</xsl:stylesheet>

Using Variables

XSL | Atul Kahate 202

XML (Variable-example.xml) <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="Variable-

example.xsl"?> <catalog> <item id="SC-001"> <maker>Reliance</maker> <description>Gas pipe</description> <size>Large</size> <price>15000</price> <currency>INR</currency> </item> </catalog>

XSL | Atul Kahate 203

XSL (Variable-example.xsl) <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:variable name="discount" select="0.10"/> <xsl:template match="catalog"> <xsl:copy> <xsl:apply-templates select="item"/> </xsl:copy> </xsl:template> <xsl:template match="item"> <xsl:copy> <xsl:attribute name="id"><xsl:value-of select="@id"/></xsl:attribute> <xsl:copy-of select="maker | description | size | price"/> <discount> <xsl:value-of select="$discount"/> </discount> <discountPrice> <xsl:value-of select="price - (price * $discount)"/> </discountPrice> <xsl:copy-of select="currency"/> </xsl:copy> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 204

Running the Example set classpath=c:\xalan\bin\

xalan.jar

java org.apache.xalan.xslt.Process -INDENT 3 -IN Variable-example.xml -XSL Variable-example.xsl -OUT output.xml

XSL | Atul Kahate 205

Using Parameters – Modified XSL <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:param name="discount" select="0.10"/> <xsl:template match="catalog"> <xsl:copy> <xsl:apply-templates select="item"/> </xsl:copy> </xsl:template> <xsl:template match="item"> <xsl:copy> <xsl:attribute name="id"><xsl:value-of select="@id"/></xsl:attribute> <xsl:copy-of select="maker | description | size | price"/> <discount> <xsl:value-of select="$discount"/> </discount> <discountPrice> <xsl:value-of select="price - (price * $discount)"/> </discountPrice> <xsl:copy-of select="currency"/> </xsl:copy> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 206

What is the Impact? We have changed variable to parameter Now, we can pass the value of discount

from the command prompt! java org.apache.xalan.xslt.Process -

INDENT 3 -param discount 0.20 -IN Variable-example.xml -XSL Variable-example-1.xsl -OUT output.xml

XSL | Atul Kahate 207

<xsl:number> Tag XML

<?xml version="1.0"?><?xml-stylesheet href="test.xsl" type="text/xsl"?><xslTutorial >

<chapter>First Chapter</chapter> <chapter>Second Chapter <chapter>Subchapter 1</chapter> <chapter>Subchapter 2</chapter> </chapter> <chapter>Third Chapter <chapter>Subchapter A</chapter> <chapter>Subchapter B <chapter>sub a</chapter> <chapter>sub b</chapter> </chapter> <chapter>Subchapter C</chapter> </chapter> </xslTutorial>

XSL<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version="1.0"> <xsl:template match="/"> <TABLE BORDER="1"> <TR><TH>Number</TH><TH>text</TH></TR> <xsl:for-each select="//chapter"> <TR><TD> <xsl:number/> </TD><TD> <xsl:value-of select="./text()"/> </TD></TR> </xsl:for-each> </TABLE> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 208

<xsl:number> Continued Change the <xsl:number> tag to

the following<xsl:number level="multiple"/>

XSL | Atul Kahate 209

Using position () XML (functions-example-2) <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="functions-example-2.xsl"?> <europe> <state>Belgium</state> <state>Germany</state> <state>United Kingdom</state> <state>France</state> <state>Spain</state> <state>Italy</state> <state>Turkey</state> <state>Sweden</state> <state>Ireland</state> <state>Greece</state> <state>Malta</state> <state>Vatican City</state> <state>Portugal</state> </europe>

XSL <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" indent="yes"/> <xsl:template match="europe"> <xsl:apply-templates select="state"/> </xsl:template> <xsl:template match="europe/state"> <xsl:value-of select="position()"/> <xsl:text>. </xsl:text> <xsl:value-of select="."/> <xsl:text>&#10;</xsl:text> </xsl:template> </xsl:stylesheet>

XSL | Atul Kahate 210

Now Using number Modified XSL <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" indent="yes"/> <xsl:template match="europe"> <xsl:apply-templates select="state"/> </xsl:template> <xsl:template match="europe/state"> <xsl:number format="1"/> <xsl:text>. </xsl:text> <xsl:value-of select="."/> <xsl:text>&#10;</xsl:text> </xsl:template> </xsl:stylesheet>

Using XSL and CSS Together

XSL | Atul Kahate 212

XML <?xml version="1.0"?> <?xml-stylesheet href="test.xsl" type="text/xsl"?> <products> <product href="http://www.playfield.com/text"> <name>Playfield Text</name> <price currency="usd">299</price> <description>Faster than the competition.</description> <version>1.0</version> </product> <product href="http://www.playfield.com/virus"> <name>Playfield Virus</name> <price currency="eur">199</price> <description> Protect yourself against malicious code. </description> <version>5.0</version> </product> <product href="http://www.playfield.com/calc"> <name>Playfield Calc</name> <price currency="usd">299</price> <description>Clear picture on your data.</description> <version>1.5</version> </product> <product href="http://www.playfield.com/db"> <name>Playfield DB</name> <price currency="cad">599</price> <description>Organize your data.</description> </product> </products>

XSL | Atul Kahate 213

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

<xsl:output method="html" indent="no"/> <xsl:template match="/products"> <html> <head> <title>Cascading Style Sheet</title> <link rel="stylesheet" type="text/css" href="table.css" title="Style"/> </head> <body> <table> <tr class="header"> <td>Name</td> <td>Price</td> <td>Description</td> </tr> <xsl:apply-templates/> </table> </body> </html> </xsl:template>

<xsl:template match="product[position() mod 2 = 1]"> <tr class="odd"> <td><xsl:value-of select="name"/></td> <td><xsl:value-of select="price"/></td> <td><xsl:value-of select="description"/></td> </tr> </xsl:template>

<xsl:template match="product"> <tr class="even"> <td><xsl:value-of select="name"/></td> <td><xsl:value-of select="price"/></td> <td><xsl:value-of select="description"/></td> </tr> </xsl:template>

</xsl:stylesheet>

XSL | Atul Kahate 214

CSS .header { background-color:

#999999; font-weight: bold; } .odd { background-color: normal; } .even { background-color: #dfdfdf;

}

Processing Multiple XML Files Using a Single XSL

XSL | Atul Kahate 216

XML File 1 (products.xml) <?xml version="1.0"?> <?xml-stylesheet href="products.xsl" type="text/xsl"?>

<products> <product href="http://www.playfield.com/text"> <name>Playfield Text</name> <price currency="usd">299</price> <description>Faster than the competition.</description> <version>1.0</version> </product> <product href="http://www.playfield.com/virus"> <name>Playfield Virus</name> <price currency="eur">199</price> <description> Protect yourself against malicious code. </description> <version>5.0</version> </product> <product href="http://www.playfield.com/calc"> <name>Playfield Calc</name> <price currency="usd">299</price> <description>Clear picture on your data.</description> <version>1.5</version> </product> <product href="http://www.playfield.com/db"> <name>Playfield DB</name> <price currency="cad">599</price> <description>Organize your data.</description> </product> </products>

XSL | Atul Kahate 217

XML File 2 (currencies.xml) <?xml version="1.0"?> <currencies> <currency> <code>eur</code> <name>Euros</name> </currency> <currency> <code>usd</code> <name>Dollars</name> </currency> <currency> <code>cad</code> <name>Canadian dollars</name> </currency> </currencies>

XSL | Atul Kahate 218

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

<xsl:output method="html" indent="no"/>

<xsl:variable name="currencies" select="document('currencies.xml')/currencies"/>

<xsl:template match="/"> <html> <head><title>Multiple documents</title></head> <body> <table> <tr bgcolor="#999999"> <td>Name</td> <td>Price</td> <td>Description</td> <td>Version</td> </tr> <xsl:apply-templates/> </table> </body> </html> </xsl:template>

<xsl:template match="product"> <xsl:variable name="currency" select="price/@currency"/> <tr> <td><xsl:value-of select="name"/></td> <td> <xsl:value-of select="price"/> <xsl:text> </xsl:text> <xsl:value-of select="$currencies/currency[code=$currency]/name"/> </td> <td><xsl:value-of select="description"/></td> <td><xsl:value-of select="version"/></td> </tr> </xsl:template>

</xsl:stylesheet>

Using XSLT and JavaScript Together (on products.xml)

XSL | Atul Kahate 220

products.xsl modified <?xml version="1.0"?>

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

<xsl:output method="html" indent="no"/>

<xsl:template match="/"> <html> <head> <title>JavaScript</title> <script language="JavaScript"><xsl:comment> // creates and initializes an array of product descriptions var urls = new Array() <xsl:for-each select="products/product"> urls[<xsl:value-of select="position()"/>] = "<xsl:value-of select="@href"/>" </xsl:for-each> // user function function doSelect(i) { open(urls[i]) } // </xsl:comment></script> </head> <body> <ul> <xsl:for-each select="products/product"> <li><a href="javascript:doSelect({position()})"> <xsl:value-of select="name"/> </a></li> </xsl:for-each>

</ul> </body> </html> </xsl:template>

</xsl:stylesheet>

Thank you!

Any Questions?

top related