5. Document Transformations

43
SDPL 2001 Notes 5: XSLT 1 5. Document Transformations 5. Document Transformations XSLT (W3C Rec. Nov-99) XSLT (W3C Rec. Nov-99) A language for transforming XML documents A language for transforming XML documents » representative of features common to tree-based representative of features common to tree-based transformation languages (DSSSL, MetaMorphosis, transformation languages (DSSSL, MetaMorphosis, TranSID, …) TranSID, …) designed to be used designed to be used » primarily as part of XSL formatting primarily as part of XSL formatting » also as an independent transformation language also as an independent transformation language Our goal: to understand the basic model and Our goal: to understand the basic model and to learn central features of the language to learn central features of the language Overview and an example Overview and an example Data model and processing model Data model and processing model

description

5. Document Transformations. XSLT (W3C Rec. Nov-99) A language for transforming XML documents representative of features common to tree-based transformation languages (DSSSL, MetaMorphosis, TranSID, …) designed to be used primarily as part of XSL formatting - PowerPoint PPT Presentation

Transcript of 5. Document Transformations

Page 1: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 1

5. Document Transformations5. Document Transformations

XSLT (W3C Rec. Nov-99)XSLT (W3C Rec. Nov-99)– A language for transforming XML documentsA language for transforming XML documents

» representative of features common to tree-based transformation representative of features common to tree-based transformation languages (DSSSL, MetaMorphosis, TranSID, …) languages (DSSSL, MetaMorphosis, TranSID, …)

– designed to be used designed to be used » primarily as part of XSL formattingprimarily as part of XSL formatting» also as an independent transformation languagealso as an independent transformation language

Our goal: to understand the basic model and Our goal: to understand the basic model and to learn central features of the languageto learn central features of the language– Overview and an exampleOverview and an example– Data model and processing modelData model and processing model

Page 2: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 2

XSLT: OverviewXSLT: Overview

XSLT uses XML syntax for expressing XSLT uses XML syntax for expressing transformationstransformations– of a document of a document source treesource tree into a into a result treeresult tree

» result and source are separate treesresult and source are separate trees

– by by template rulestemplate rules Each (normal) template rules hasEach (normal) template rules has

– aa pattern pattern (matched against nodes of the source tree) (matched against nodes of the source tree)– a a template template as a bodyas a body

» instantiated to create fragments of the result treeinstantiated to create fragments of the result tree

Page 3: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 3

Trans form ation P rocess

O utput P ro cess

X M L

T ext

H T M L

S tyleS heet

SourceDocument

Sourc e TreeR esult T ree

Overview of XSLT TransformationOverview of XSLT Transformation

Page 4: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 4

Style Sheets and Template RulesStyle Sheets and Template Rules

AnAn xsl:stylesheetxsl:stylesheet (or(or xsl:transformxsl:transform) ) consists of template rules:consists of template rules:<xsl:template match="<xsl:template match="PatternPattern">">

TemplateTemplate <!-- <!-- NB: well-formed XMLNB: well-formed XML --> --></xsl:template></xsl:template>

TemplateTemplate consists of consists of» literal result tree fragments (elements, text), and literal result tree fragments (elements, text), and » XSLT instructions for creating further result tree fragments XSLT instructions for creating further result tree fragments

Rule applied only to nodes of source tree Rule applied only to nodes of source tree matched by the matched by the PatternPattern – expressed using XML Path Language (XPath)expressed using XML Path Language (XPath)

Page 5: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 5

XPath in ShortXPath in Short

W3C Recommendation (16-Nov-99)W3C Recommendation (16-Nov-99)– a compact non-XML syntax for a compact non-XML syntax for addressing addressing

parts of XML documentsparts of XML documents– used also by XLink and XPointer languagesused also by XLink and XPointer languages

» W3C drafts for describing hyperlinks in XMLW3C drafts for describing hyperlinks in XML

– provides typical basic operations for provides typical basic operations for manipulation of manipulation of strings, numbersstrings, numbers and and truth truth valuesvalues

Page 6: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 6

An XSL transformation exampleAn XSL transformation example

Transform below XML document to HTML:Transform below XML document to HTML:<?xml version='1.0'?><?xml version='1.0'?>

<?xml-stylesheet type="text/xsl" href="walsh.xsl" ?><?xml-stylesheet type="text/xsl" href="walsh.xsl" ?>

<!-- Modified from an example by Norman Walsh --> <!-- Modified from an example by Norman Walsh -->

<doc><title>My Document</title><doc><title>My Document</title>

<para>This is a <em>short</em> document.</para><para>This is a <em>short</em> document.</para>

<para>It only exists to <em>demonstrate a <para>It only exists to <em>demonstrate a

<em>simple</em> XML document</em>.</para><em>simple</em> XML document</em>.</para>

<figure><title>My Figure</title> <figure><title>My Figure</title>

<graphic fileref="myfig.jpg"/></figure><graphic fileref="myfig.jpg"/></figure>

</doc></doc>

Page 7: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 7

Example (style sheet begins)Example (style sheet begins)

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

<xsl:template match="<xsl:template match="//"> <!-- rule for root -->"> <!-- rule for root --> <HTML><HEAD><TITLE>A Document</TITLE></HEAD> <HTML><HEAD><TITLE>A Document</TITLE></HEAD> <BODY> <BODY> <!-- process root's children here: --><!-- process root's children here: -->

<xsl:apply-templates /> <xsl:apply-templates /> </BODY></BODY> </HTML> </HTML> </xsl:template></xsl:template>

<xsl:template match="<xsl:template match="doc/titledoc/title"> "> <H1><xsl:apply-templates /></H1> <H1><xsl:apply-templates /></H1>

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

Page 8: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 8

Example (Example (paraparass and and emphemphs)s)

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

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

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

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

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

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

Page 9: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 9

Example (Example (figurefigures)s)

<xsl:template match="<xsl:template match="figurefigure"> "> <!-- Insert a bold caption of form '<!-- Insert a bold caption of form 'Figure Num.Figure Num. ' '

by counting all figures in the document: --> by counting all figures in the document: --><DIV><B>Figure <xsl:number level="any" <DIV><B>Figure <xsl:number level="any"

count="figure"/>. </B> count="figure"/>. </B> <BR /> <BR /> <!-- Process the children of figure, --><!-- Process the children of figure, --><!-- the 'graphic' child first: --><!-- the 'graphic' child first: --><xsl:apply-templates select="<xsl:apply-templates select="graphicgraphic" /> " />

<!-- then the 'title' child: --><!-- then the 'title' child: --><xsl:apply-templates select="<xsl:apply-templates select="titletitle" /> " />

</DIV></DIV>

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

Page 10: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 10

Example (end of style sheet)Example (end of style sheet)

<xsl:template match="<xsl:template match="graphicgraphic"> "> <IMG> <!-- Create new attribute 'src': --> <IMG> <!-- Create new attribute 'src': --> <xsl:attribute name=" <xsl:attribute name="srcsrc"> "> <!-- and assign the value of current <!-- and assign the value of current element's fileref attribute to it: --> element's fileref attribute to it: -->

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

</IMG> </IMG> </xsl:template></xsl:template> <!-- enclose figure title in a B element: --><!-- enclose figure title in a B element: --><xsl:template match="<xsl:template match="figure/titlefigure/title"> ">

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

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

Page 11: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 11

Result (edited for readability)Result (edited for readability)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">Transitional//EN">

<HTML><HEAD><TITLE>A Document</TITLE></HEAD><HTML><HEAD><TITLE>A Document</TITLE></HEAD>

<BODY> <H1>My Document</H1><BODY> <H1>My Document</H1>

<P>This is a <I>short</I> document.</P><P>This is a <I>short</I> document.</P>

<P>It only exists to <I>demonstrate a <B>simple</B> XML <P>It only exists to <I>demonstrate a <B>simple</B> XML document</I>.</P>document</I>.</P>

<DIV><DIV>

<B>Figure 1. </B> <BR><B>Figure 1. </B> <BR>

<IMG src="myfig.jpg"><B>My Figure</B><IMG src="myfig.jpg"><B>My Figure</B>

</DIV></DIV>

</BODY></BODY>

</HTML></HTML>

Page 12: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 12

Prospects of XSL or XSLTProspects of XSL or XSLT

XSL can be used in different waysXSL can be used in different ways– for online document deliveryfor online document delivery

» in a Web serverin a Web server» in a Web browser (if the browser supports)in a Web browser (if the browser supports)

– for offline document manipulationfor offline document manipulation» transform XML into other form (XML/HTML/text) transform XML into other form (XML/HTML/text)

using XSLTusing XSLT

– for offline document formattingfor offline document formatting» produce, say, PDF from XML by an XSL style sheet produce, say, PDF from XML by an XSL style sheet

(using XSLT + XSL formatting objects)(using XSLT + XSL formatting objects)

Page 13: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 13

XSLT in online document deliveryXSLT in online document delivery

XSLT in a browserXSLT in a browser– defines rendering of XML documentsdefines rendering of XML documents– approach of Microsoft Internet Explorer 5approach of Microsoft Internet Explorer 5

» transformation of XML to HTML on the fly in browsertransformation of XML to HTML on the fly in browser» NBNB: Microsoft's XSLT implementation differs from XSLT 1.0: Microsoft's XSLT implementation differs from XSLT 1.0

(a new one exists but has to be installed separately)(a new one exists but has to be installed separately)

XSLT in a Web serverXSLT in a Web server– an HTTP request for an XML document served by an HTTP request for an XML document served by

transforming XML on the fly to HTML (or other format) transforming XML on the fly to HTML (or other format) in the serverin the server

Page 14: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 14

XSLT/XPath Data ModelXSLT/XPath Data Model

XSLT and XPath have a common data modelXSLT and XPath have a common data model Documents viewed as abstract, logical tree Documents viewed as abstract, logical tree

structuresstructures Seven types of tree nodesSeven types of tree nodes

– rootroot (additional parent of document element) (additional parent of document element)– elementelement nodes nodes– attributeattribute nodes nodes– texttext nodes nodes– nodes for nodes for commentscomments, , processing instructionsprocessing instructions and and

namespacesnamespaces NBNB: Entities are expanded : Entities are expanded no entity nodes no entity nodes

Page 15: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 15

XSLT/XPath document treesXSLT/XPath document trees

Element nodes have element nodes, text nodes, Element nodes have element nodes, text nodes, comment nodes and processing instruction nodes comment nodes and processing instruction nodes of their (direct) content as childrenof their (direct) content as children– NB: attribute nodes not viewed as childrenNB: attribute nodes not viewed as children– the the valuevalue of an element node is the concatenation of its of an element node is the concatenation of its

text-node descendantstext-node descendants Nodes have a complete Nodes have a complete document orderdocument order

– root node first, otherwise according to the order of the root node first, otherwise according to the order of the first character of the XML markup for each nodefirst character of the XML markup for each node

– > element node precedes it's attribute nodes, which > element node precedes it's attribute nodes, which precede any content nodes of the elementprecede any content nodes of the element

Page 16: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 16

XSLT/XPath trees: ExampleXSLT/XPath trees: Example

Similar to the DOM structure model, with slight Similar to the DOM structure model, with slight differencesdifferences– value of an element: its full textual content value of an element: its full textual content

(In DOM: (In DOM: nullnull))– no names for text nodes, comment nodes, etc.no names for text nodes, comment nodes, etc.

(In DOM: (In DOM: "#text""#text", , "#comment""#comment", etc. , etc.

Example document:Example document:<article>Written by <fig file="pekka.jpg" <article>Written by <fig file="pekka.jpg"

caption="The caption="The Lecturer"/> Lecturer"/> the lecturer.</article>the lecturer.</article>

Page 17: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 17

XSLT/XPath trees: ExampleXSLT/XPath trees: Example

"W ritte n b y the le c ture r."

"W ritte n b y the le c ture r."

root

""

elem ent

"artic le "

text

""

"W ritte n b y "

elem ent

"f ig "

""

text

""

" the le c ture r."

attribute attribute

"cap tio n" "f ile "

"The Lec turer" "p e kka.jp g "

Legend: type

value

nam e

Page 18: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 18

XPath ExpressionsXPath Expressions

Used for selecting source tree nodes, conditional Used for selecting source tree nodes, conditional processing, and generating new text contentprocessing, and generating new text content– return return node-sets, truth values, numbers node-sets, truth values, numbers oror strings strings– XSLT can select any parts of source tree for XSLT can select any parts of source tree for

processing using node-set valued expressionsprocessing using node-set valued expressions Location pathsLocation paths

– the most characteristic of XPath expressionsthe most characteristic of XPath expressions– evaluated with respect to a evaluated with respect to a context nodecontext node

» often the often the current nodecurrent node matched by the template pattern matched by the template pattern

– resultresult: set of nodes selected by the location path: set of nodes selected by the location path

Page 19: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 19

Location paths (1)Location paths (1)

Consist of Consist of location stepslocation steps separated by ' separated by '//''– each step produces a set of nodeseach step produces a set of nodes– steps evaluated left-to-right, steps evaluated left-to-right,

each node in turn acting as a context nodeeach node in turn acting as a context node Each location step is of form Each location step is of form

AxisNameAxisName:::: NodeTestNodeTest ( ([[PredicateExprPredicateExpr]])*)*

– axisaxis specifies the tree relationship between the context specifies the tree relationship between the context node and the selected nodes node and the selected nodes

– node testnode test restricts the type and and name of nodes restricts the type and and name of nodes– further filtered by 0 or more further filtered by 0 or more predicatespredicates

Page 20: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 20

Location paths (2)Location paths (2)

In total 13 axesIn total 13 axes– child, descendant, parent, ancestor, following-child, descendant, parent, ancestor, following-sibling, preceding-sibling, following, preceding, sibling, preceding-sibling, following, preceding, attribute, self, descendant-or-self, ancestor-or-attribute, self, descendant-or-self, ancestor-or-self, namespaceself, namespace

Node tests (slightly simplified)Node tests (slightly simplified)– NameName: any element node with name : any element node with name NameName

(on an attribute axis, any attribute node with name (on an attribute axis, any attribute node with name NameName))– **: any element node (on an attribute axis, any attribute node): any element node (on an attribute axis, any attribute node)– text()text(): any text node: any text node– node()node(): any node of any type: any node of any type

Page 21: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 21

Location paths (3)Location paths (3)

Abbreviations in location stepsAbbreviations in location steps– 'child::''child::' can be omitted can be omitted– 'attribute::''attribute::' can be shortened to can be shortened to ''@@''– ''/descendant-or-self::node()/'/descendant-or-self::node()/' shortened to shortened to ''////''

("go down any number of levels")("go down any number of levels")– 'self::node()''self::node()' can be shortened to can be shortened to ''..'' (period)(period)– 'parent::node()''parent::node()' can be shortened to can be shortened to ''....''

– Predicate 'Predicate '[position()=[position()=nn]]' for testing occurrence position ' for testing occurrence position nn can can be shortened to'be shortened to' [ [nn]]''

''//' ' in the beginning sets context to the root nodein the beginning sets context to the root node Syntax resembles Linux/Unix file path namesSyntax resembles Linux/Unix file path names

Page 22: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 22

XPath Axes and Their OrientationXPath Axes and Their Orientation

Axes are oriented away from the context nodeAxes are oriented away from the context node(except (except attribute attribute and and namespace namespace axes, which are axes, which are unordered sets)unordered sets)– the the position() position() for the closest node for the closest node = 1 = 1– for the most remote node, for the most remote node, position() = last()position() = last()

1

C o nte xtno de :

The simplest axis,The simplest axis, self: self:

Page 23: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 23

XPath Axes and Their OrientationXPath Axes and Their Orientation

parent:parent:

1 C ontextnode :

Page 24: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 24

XPath Axes and Their OrientationXPath Axes and Their Orientation

ancestor:ancestor: 2

1

ancestor-or-self:ancestor-or-self:3

2

1

Page 25: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 25

XPath Axes and Their OrientationXPath Axes and Their Orientation

child:child:

431 2

C ontextnode :

Page 26: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 26

XPath Axes and Their OrientationXPath Axes and Their Orientation

descendant:descendant:

871 4

2 3 65 9

descendant-or-self:descendant-or-self: 1

982 5

3 4 76 1 0

Page 27: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 27

XPath Axes and Their OrientationXPath Axes and Their Orientation

preceding-sibling:preceding-sibling:

2 1

following-sibling:following-sibling:

21

Page 28: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 28

XPath Axes and Their OrientationXPath Axes and Their Orientation

following :following :

21

3

preceding:preceding:

3

2 1

Page 29: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 29

Location path examples (1)Location path examples (1)

chapchap children of current node:children of current node: ./chap./chap (or equivalently:(or equivalently: chapchap))

The document element The document element (child element of root node):(child element of root node): /*/*

Elements Elements author author anywhere (below the root): anywhere (below the root): //author//author

All All chapterchapters with attributes with attribute type="intro"type="intro": : //chapter[@type='intro']//chapter[@type='intro']

the previousthe previous chapter chapter siblingsibling: : preceding-sibling::chapter[position()=1]preceding-sibling::chapter[position()=1]

Page 30: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 30

Location path examples (2)Location path examples (2)

All child elements having an attributeAll child elements having an attribute typetype: : *[@type]*[@type]

NBNB: use of node sets as truth values: : use of node sets as truth values: empty - empty - falsefalse; non-empty - ; non-empty - truetrue

All child elements of anyAll child elements of any author author child:child: author/*author/*

sectsections whoseions whose type type attribute equalsattribute equals style style attribute of the document element:attribute of the document element:

//sect[@type = /*/@style]//sect[@type = /*/@style] First First authorauthor child, and previous to the last: child, and previous to the last:

author[1], author[last()-1]author[1], author[last()-1]

Page 31: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 31

Location path examples (3)Location path examples (3)

Predicate expressions can be Boolean Predicate expressions can be Boolean combinations:combinations:– child elements child elements authorauthor with a with a publpubl child, but without child, but without degreedegree or or awardaward children:children:

author[publ and not(degree or award)]author[publ and not(degree or award)] Closest Closest chapchap ancestor (and highest):ancestor (and highest):

ancestor::chap[1] ancestor::chap[1] (ancestor::chap[last()]) (ancestor::chap[last()])

authorauthor of the highestof the highest chapchap ancestor that is ancestor that is contained in ancontained in an appappendix: endix: ancestor::chap[ancestor::app][last()]/authorancestor::chap[ancestor::app][last()]/author

Page 32: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 32

XSLT PatternsXSLT Patterns

Main use in match attributes of template rules:Main use in match attributes of template rules:<xsl:template match="<xsl:template match="PatternPattern">">

Expressions specifying conditions on a nodeExpressions specifying conditions on a node– Location paths that use onlyLocation paths that use only childchild and and attributeattribute axes axes

and operatorsand operators ' '////' ' and and ''//''

– may begin withmay begin with id(id(''IdValIdVal''))(for selecting element nodes by ID attribute values)(for selecting element nodes by ID attribute values)

– can use arbitrary predicate expressions can use arbitrary predicate expressions [[ExprExpr]]– alternatives may be separated by 'alternatives may be separated by '||' ' (node-set union (node-set union

operator)operator)

Page 33: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 33

XSLT Patterns: SemanticsXSLT Patterns: Semantics

A location path pattern A location path pattern PP is of form is of form StepStep11§ § StepStep2 2 § …§ § …§ StepStepnn-1-1§ § StepStepn n ,,

where each separator § is either 'where each separator § is either '//' or '' or '////' ' Pattern Pattern PP matches a node matches a node nn iff the rightmost step iff the rightmost step

StepStepn n matches matches nn and a suitable node and a suitable node v v matches matches

the prefix the prefix StepStep11§ § StepStep2 2 § …§ § …§ StepStepnn-1 -1 of of PP : :– if the rightmost § is 'if the rightmost § is '//'', , vv has to be the parent of has to be the parent of nn– if the rightmost § is 'if the rightmost § is '////', ', vv can be any ancestor of can be any ancestor of nn

Page 34: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 34

XSLT Patterns: ExamplesXSLT Patterns: Examples

PatternPattern sect-head | section/head sect-head | section/head

matches any element node with namematches any element node with name sect-headsect-head, and , and anyany headhead elements directly below aelements directly below a sectionsection

For a match with patternFor a match with pattern appendix//ulist/item[1] appendix//ulist/item[1]

a node has to be the first a node has to be the first itemitem element in aelement in a ulistulist element which is contained in anelement which is contained in an appendixappendix

Page 35: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 35

XSLT Processing ModelXSLT Processing Model

0. document parsed into 0. document parsed into source treesource tree

1. 1. Result treeResult tree constructed by applying constructed by applying template template rulesrules to the source tree to the source tree» may contain text, formatting objects and arbitrary may contain text, formatting objects and arbitrary

elementselements

2. result tree interpreted to produce formatted 2. result tree interpreted to produce formatted output (XSL), or serialized (as XML, HTML or output (XSL), or serialized (as XML, HTML or text)text)

Page 36: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 36

XSL Tree ConstructionXSL Tree Construction

Start at the source tree root; Start at the source tree root;

whilewhile (unprocessed source nodes left) (unprocessed source nodes left) dodo

Find matching template rules; Find matching template rules; Choose one rule (the one with highest Choose one rule (the one with highest prioritypriority););

Instantiate rule’s template in the context of the current Instantiate rule’s template in the context of the current node; Add the result to the result tree;node; Add the result to the result tree;

Recursively process any source nodes selected by XSLT Recursively process any source nodes selected by XSLT instructions (instructions (apply-templates, for-eachapply-templates, for-each) in the ) in the template;template;

endwhileendwhile;;

Page 37: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 37

Selecting among multiple matching rulesSelecting among multiple matching rules

Priority of a rule can be specified by numerical Priority of a rule can be specified by numerical attribute: attribute: <xsl:template priority="<xsl:template priority="2.02.0">">

Default prioritiesDefault priorities– 0 for simple name tests 0 for simple name tests (like (like para, @hrefpara, @href))– negative for less specific patterns negative for less specific patterns

e.g., e.g., *, @*, node()*, @*, node()– 0.5 for more complex patterns0.5 for more complex patterns

Multiple matching rules with the same maximum Multiple matching rules with the same maximum priority is an error - Processor may recover by priority is an error - Processor may recover by (silently) choosing the (silently) choosing the last onelast one of those rules of those rules

Page 38: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 38

Application of template rulesApplication of template rules

Without a Without a selectselect attribute attribute <xsl:apply-templates /><xsl:apply-templates />

processes all children of current nodeprocesses all children of current node– > > Default behaviour: top-down traversal of source treeDefault behaviour: top-down traversal of source tree

Otherwise theOtherwise the selectselected nodes are processed ed nodes are processed – in in document order document order (Order a major distinction to typical (Order a major distinction to typical

database query languages)database query languages)

Built-in rulesBuilt-in rules allow recursive traversal to proceed allow recursive traversal to proceed gracefully in the absence of matching rules gracefully in the absence of matching rules

Page 39: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 39

Default rules for elements and contentDefault rules for elements and content

Built-in rule for the root and element nodes:Built-in rule for the root and element nodes: <xsl:template match="/ | *"><xsl:template match="/ | *">

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

Built-in rule for text and attribute nodes:Built-in rule for text and attribute nodes: <xsl:template match="text() | @*"><xsl:template match="text() | @*"><!-- Insert the string value <!-- Insert the string value

of current node: -->of current node: --> <xsl:value-of select="." /><xsl:value-of select="." />

</xsl:template</xsl:template>> Low priorityLow priority can be overriddencan be overridden

Page 40: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 40

A result tree construction example A result tree construction example

Consider transforming documentConsider transforming document<A><A><C>c1</C><B>bb<C>c2</C></B><D>dd</D><C>c3</C><C>c1</C><B>bb<C>c2</C></B><D>dd</D><C>c3</C></A></A>

with below rules:with below rules:<xsl:template match="/"> <!-- Rule 1 --><xsl:template match="/"> <!-- Rule 1 -->

<xsl:apply-templates select="//B" /><xsl:apply-templates select="//B" /></xsl:template></xsl:template>

<xsl:template match="B"> <!-- Rule 2 --><xsl:template match="B"> <!-- Rule 2 --><NewB>New Content <xsl:apply-templates <NewB>New Content <xsl:apply-templates select="../C" /> <xsl:apply-templates /> select="../C" /> <xsl:apply-templates /> </NewB></NewB>

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

Page 41: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 41

Construction example (2)Construction example (2)

The resultThe result<NewB>New Content c1c3bbc2</NewB><NewB>New Content c1c3bbc2</NewB>

is obtained as follows: is obtained as follows: 1. 1. Rule 1 withRule 1 with match="/" match="/" matches the root node.matches the root node.

Instruction Instruction <xsl:apply-templates select="//B" /><xsl:apply-templates select="//B" /> selects theselects the BB element node for processing.element node for processing.

2. 2. Rule 2 with patternRule 2 with pattern "B" "B" creates into result tree acreates into result tree a NewB NewB element node with text node element node with text node ""New ContentNew Content " " as its first as its first child.child.

Page 42: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 42

Construction example (3)Construction example (3)

3. Instruction 3. Instruction <xsl:apply-templates select="../C"/><xsl:apply-templates select="../C"/> selects element selects element CC siblings of current node (siblings of current node (BB) for ) for processing. The built-in element rule applies to these, and processing. The built-in element rule applies to these, and the built-in text rule to their children. the built-in text rule to their children. Result: text nodesResult: text nodes " "c1c1" " and and ""c3c3" " become the next become the next children ofchildren of NewBNewB..

4. Instruction 4. Instruction <xsl:apply-templates /><xsl:apply-templates /> in the context of in the context of element node element node BB selects its children, selects its children, ""bb"bb" and and <C>c2</C><C>c2</C>, for processing. The text node is copied to , for processing. The text node is copied to result tree by the built-in text rule, and theresult tree by the built-in text rule, and the C C element element node becomesnode becomes "c2""c2" in the result (similarly to step 3). in the result (similarly to step 3).

Page 43: 5. Document Transformations

SDPL 2001 Notes 5: XSLT 43

Is it Really So Complex?Is it Really So Complex?

Yes, and NoYes, and No XSLT is high-level declarative language for XSLT is high-level declarative language for

describing transformationsdescribing transformations– Normally no need to think about execution in so much Normally no need to think about execution in so much

detail; Often sufficient just to specify declarative rules detail; Often sufficient just to specify declarative rules to handle different casesto handle different cases

– A computer scientist wants to understand how a model A computer scientist wants to understand how a model really works … really works …