sdpl 2011xslt: additional features & computing1 4.1 additional xslt features n xpath for...

66
SDPL 2011 XSLT: Additional features & Computing 1 4.1 Additional XSLT Features 4.1 Additional XSLT Features XPath for arithmetics, cross- XPath for arithmetics, cross- references, and string manipulation references, and string manipulation Generating text Generating text for content for content for attribute values for attribute values Repetition, sorting and conditional Repetition, sorting and conditional processing processing Numbering document contents Numbering document contents 4.2 Computing with XSLT 4.2 Computing with XSLT

Upload: manuel-lillywhite

Post on 15-Dec-2015

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 1

4.1 Additional XSLT Features 4.1 Additional XSLT Features

XPath for arithmetics, cross-references, and XPath for arithmetics, cross-references, and string manipulation string manipulation

Generating textGenerating text– for contentfor content– for attribute valuesfor attribute values

Repetition, sorting and conditional processingRepetition, sorting and conditional processing Numbering document contentsNumbering document contents

4.2 Computing with XSLT 4.2 Computing with XSLT

Page 2: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 2

XPath: ArithmeticsXPath: Arithmetics

Double-precision floating-point operators Double-precision floating-point operators ++, , --, , **, , divdiv, , modmod (same as (same as %% in Java)in Java)

» e.g. e.g. 2.3 mod 1.12.3 mod 1.1 ≈ 0.1≈ 0.1 Truncating numbers, and rounding up/to the closest int:Truncating numbers, and rounding up/to the closest int:

floor(x)floor(x), , ceiling(x)ceiling(x), , round(x)round(x)

Formatting numbers as strings (e.g.):Formatting numbers as strings (e.g.):

» format-number(-1.2534, format-number(-1.2534, ""0.00.0"") = ) = ""-1.3-1.3""

– XSLTXSLT 1.0 function; uses Java 1.0 function; uses Java DecimalFormatDecimalFormat patterns patterns

Page 3: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 3

Aggregate FunctionsAggregate Functions

Counting nodes Counting nodes » count(count(node-setnode-set))

– and summing them as numbers and summing them as numbers » sum(sum(node-setnode-set))

Example: Example: – Average of observed temps below current node:Average of observed temps below current node:sum(sum(.//obs/@temperature.//obs/@temperature))

divdiv count( count(.//obs.//obs))

Page 4: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 4

Cross-referencingCross-referencing

Function Function idid selects elements by their unique IDselects elements by their unique ID– NBNB: ID attributes must be declared in DTD: ID attributes must be declared in DTD

(See an example later)(See an example later)

Examples:Examples:– id('sec:intro')id('sec:intro')

selects the element with unique IDselects the element with unique ID ""sec:introsec:intro""– id('sec:intro')/auth[3]id('sec:intro')/auth[3]

selects the thirdselects the third authauth of the above elementof the above element– id('sec1 sec2 sec3')id('sec1 sec2 sec3')selects 3 sections selects 3 sections

(with corresponding ID values)(with corresponding ID values)

Page 5: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 5

String manipulationString manipulation

Equality and inequality of strings with Equality and inequality of strings with operatorsoperators == andand !=!=– "foo" = 'foo'"foo" = 'foo'; ; (NB alternative quotes)(NB alternative quotes)– "foo" != "Foo""foo" != "Foo"

Testing for substrings:Testing for substrings:– starts-with("starts-with("dogdogbert", "bert", "dogdog") = true()") = true()– contains("docontains("dogbegbert", "rt", "gbegbe") = true()") = true()

Concatenation (of two or more strings), Concatenation (of two or more strings), – concat("dog", "bert") = "dogbert"concat("dog", "bert") = "dogbert"

Page 6: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 6

More XPath string functionsMore XPath string functions

– substring-before("ftp:substring-before("ftp:////a", "a", "////") = ") = substring-before("ftp:substring-before("ftp:///a", "/a", "//") = "ftp:"") = "ftp:"

– substring-after("ftp:substring-after("ftp:///a", "/a", "//")= "/a"")= "/a"– string-length("dogbert")=7string-length("dogbert")=7– substring(substring(string, start, length?string, start, length?):):

» substring("dogbert", 1, 3) = "dog"substring("dogbert", 1, 3) = "dog"» substring("dogbert", 3) = "gbert"substring("dogbert", 3) = "gbert"

– translate(translate(Str, Replaced, ReplacingStr, Replaced, Replacing):):» translate("translate("doggdoggy","y","dgodgo","Ssi") = "Sissy"","Ssi") = "Sissy"

Page 7: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 7

Generating TextGenerating Text

Insert text nodes with a computed value in the result:Insert text nodes with a computed value in the result:<<xsl:value-ofxsl:value-of select=" select="ExprExpr" />" />

– if if ExprExpr gives a node-set, the gives a node-set, the value of the first nodevalue of the first node in in document order is used (in XSLT 2.0 all, space-separated)document order is used (in XSLT 2.0 all, space-separated)

Example: Transform elements likeExample: Transform elements like

<name alias="Bird"><name alias="Bird"><first>Charlie</first><last>Parker</last><first>Charlie</first><last>Parker</last>

</name></name>

to the formto the form

Charlie Charlie ("("BirdBird")") Parker Parker

Page 8: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 8

Computing generated text (2)Computing generated text (2)

This can be specified by template ruleThis can be specified by template rule<xsl:template match="name"><xsl:template match="name"><xsl:<xsl:value-ofvalue-of select="first" /> select="first" />("("<xsl:<xsl:value-ofvalue-of select="@alias" /> select="@alias" />")") <xsl:<xsl:value-ofvalue-of select="last" /> select="last" /> <xsl:text><xsl:text></xsl:text></xsl:text></xsl:template></xsl:template>

xsl:textxsl:text is seldom needed, but useful for is seldom needed, but useful for including whitespace text including whitespace text

Page 9: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 9

Attribute value templatesAttribute value templates

Expression string-values can be inserted in Expression string-values can be inserted in attribute values by enclosing expressions in attribute values by enclosing expressions in bracesbraces {{ andand }}

Example: Transform source elementExample: Transform source element<photo><photo>

<file><file>Mary.jpgMary.jpg</file></file> <size width="300"/><size width="300"/>

</photo></photo>into forminto form

<img src="/images/<img src="/images/Mary.jpgMary.jpg" " width="300" />width="300" />

Page 10: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 10

Attribute value templates (2)Attribute value templates (2)

This can be specified by template ruleThis can be specified by template rule<xsl:template match="photo"><xsl:template match="photo">

<img src="/images/<img src="/images/{file}{file}""width="width="{size/@width}{size/@width}" />" />

</xsl:template></xsl:template> ExpressionsExpressions {file}{file} andand {size/@width}{size/@width} are are

evaluated in the context of the current node (the evaluated in the context of the current node (the photophoto element)element)

Page 11: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 11

XSLT: RepetitionXSLT: Repetition

Nodes can be "pulled" from source for Nodes can be "pulled" from source for processing using processing using

<<xsl:for-eachxsl:for-each select=" select="ExprExpr">">TemplateTemplate

</</xsl:for-eachxsl:for-each>>

– TemplateTemplate is applied to the selected nodelist, is applied to the selected nodelist, each node in turn as the each node in turn as the current()current() node node» in document order, unless sorted using in document order, unless sorted using xsl:sortxsl:sort

instructions (see later)instructions (see later)

Page 12: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 12

Example (of Example (of for-eachfor-each))

Format the below document as HTML:Format the below document as HTML:<!DOCTYPE document [ <!ATTLIST section id ID #IMPLIED> ]><!DOCTYPE document [ <!ATTLIST section id ID #IMPLIED> ]><document> <title>The Joy of XML</title> <document> <title>The Joy of XML</title> <section id="Intro"><title>Getting Started</title> <section id="Intro"><title>Getting Started</title> <name><first>Helen</first> <last>Brown</last></name> <name><first>Helen</first> <last>Brown</last></name> says that processing XML documents is fun. says that processing XML documents is fun. <name><first>Dave</first> <last>Dobrik</last></name> agrees. <name><first>Dave</first> <last>Dobrik</last></name> agrees. </section> </section> <section><title>Family affairs</title> <section><title>Family affairs</title> <name><first>Bob</first> <last>Brown</last></name> is the <name><first>Bob</first> <last>Brown</last></name> is the husband of <name><first>Helen</first> husband of <name><first>Helen</first> <last>Brown</last></name>. </section> <last>Brown</last></name>. </section> <section><title>Finishing Up</title> <section><title>Finishing Up</title> As we discussed in <title-ref idref="Intro" />, processing XML As we discussed in <title-ref idref="Intro" />, processing XML documents is fun. </section></document>documents is fun. </section></document>

Page 13: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 13

Example: Table of contentsExample: Table of contents

A table of contents can be formed of section titles:A table of contents can be formed of section titles:<xsl:template match="/"><xsl:template match="/"><HTML><HEAD> <TITLE><xsl:value-of <HTML><HEAD> <TITLE><xsl:value-of

select="document/title"/></TITLE></HEAD> select="document/title"/></TITLE></HEAD> <BODY> <BODY> <H2>Table of Contents</H2> <H2>Table of Contents</H2> <OL> <!-- Pull each section title: --> <OL> <!-- Pull each section title: --> <xsl: <xsl:for-eachfor-each select="//section/title"> select="//section/title"> <LI><xsl:apply-templates /></LI> <LI><xsl:apply-templates /></LI> </xsl: </xsl:for-eachfor-each>> </OL> <!-- then process the sections: --> </OL> <!-- then process the sections: --> <xsl:apply-templates select="document/section"/> <xsl:apply-templates select="document/section"/>

</BODY> </HTML> </BODY> </HTML></xsl:template></xsl:template>

Page 14: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 14

Example (cont; Cross references)Example (cont; Cross references)

Cross-refs can also be processed usingCross-refs can also be processed using for-eachfor-each: : <xsl:template match="title-ref"> <xsl:template match="title-ref"> <xsl:for-each select="id(@idref)"> <xsl:for-each select="id(@idref)"> <!-- just one selected --><!-- just one selected --> Section (<xsl:value-of Section (<xsl:value-of

select="substring(title, 1, 8)" />...)select="substring(title, 1, 8)" />...) </xsl:for-each></xsl:for-each></xsl:template></xsl:template>

With this rule the source fragment With this rule the source fragment As we discussed in <title-ref idref="Intro"/>As we discussed in <title-ref idref="Intro"/>

becomesbecomesAs we discussed in Section (Getting …)As we discussed in Section (Getting …)

Page 15: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 15

XSLT SortingXSLT Sorting

Nodes can be processed in sorted order, by Nodes can be processed in sorted order, by xsl:for-xsl:for-eacheach or or xls:apply-templates, xls:apply-templates, with with <<xsl:sortxsl:sort/>/>

controlled by attributes ofcontrolled by attributes of xsl:sortxsl:sort, like, like– selectselect: expression for the sort key (default: : expression for the sort key (default: ".""."))– data-typedata-type: : "text""text" (default) or(default) or "number""number" – orderorder:: "ascending""ascending" (default) (default)

or or "descending""descending" The first The first xsl:sortxsl:sort specifies the primary sort key, specifies the primary sort key,

the second one the secondary sort key, and so on.the second one the secondary sort key, and so on.

Page 16: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 16

Example (cont; Sorted index of names)Example (cont; Sorted index of names)

All names can be collected in a last-name-first-name order All names can be collected in a last-name-first-name order using the below templateusing the below template<H2>Index</H2> <UL><H2>Index</H2> <UL> <xsl:for-each select="//name"> <xsl:for-each select="//name"> < <xsl:sortxsl:sort select="last" /> select="last" /> < <xsl:sortxsl:sort select="first" /> select="first" /> <LI><xsl:value-of select="last" <LI><xsl:value-of select="last" />, <xsl:value-of select="first"/></LI> />, <xsl:value-of select="first"/></LI> </xsl:for-each> </xsl:for-each></UL></UL>

This creates an UL list with itemsThis creates an UL list with items<LI>Brown, Bob</LI> <LI>Brown, Bob</LI> <LI>Brown, Helen</LI> <LI>Brown, Helen</LI> <LI>Brown, Helen</LI> <LI>Brown, Helen</LI> <LI>Dobrik, Dave</LI><LI>Dobrik, Dave</LI>

Possible to eliminate duplicates?Possible to eliminate duplicates?Yes, but a bit tricky. See nextYes, but a bit tricky. See next

Page 17: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 17

Conditional processingConditional processing

A template can be instantiated or ignored withA template can be instantiated or ignored with<xsl:if<xsl:if test="test="BooleanExprBooleanExpr">">

TemplateTemplate</xsl:if></xsl:if>

Example: a comma-separated list of names:Example: a comma-separated list of names:<xsl:template match="namelist/name"><xsl:template match="namelist/name"> <xsl:apply-templates/> <xsl:apply-templates/> < <xsl:ifxsl:if test="test="position() &lt; last()position() &lt; last()"" > >,, </</xsl:ifxsl:if>></xsl:template></xsl:template>

Page 18: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 18

An aside: Meaning of An aside: Meaning of position()position()

Evaluation wrt the current node list. The above applied to Evaluation wrt the current node list. The above applied to

<namelist><name>a</name><name>b</name></namelist> <namelist><name>a</name><name>b</name></namelist> <namelist><name>c</name><name>d</name></namelist><namelist><name>c</name><name>d</name></namelist>

by invocationby invocation

<xsl:apply-templates select="//name" /><xsl:apply-templates select="//name" /> yieldsyields ""aa,,bb,,cc,,dd" " ( (←← single node list); single node list);

With invocation fromWith invocation from <xsl:template match="namelist"><xsl:template match="namelist">

<xsl:apply-templates select="name" /><xsl:apply-templates select="name" />

we'd getwe'd get ""aa,,bb"" andand ""cc,,dd"" (Clever!) (Clever!)

Page 19: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 19

Conditional processing (2)Conditional processing (2)

A case construct (A case construct ( switchswitch in Java): in Java): <xsl:choose><xsl:choose>

<!-- The first '<!-- The first 'whenwhen' whose ' whose test=true()test=true() is is instantiated: -->instantiated: -->

<xsl:when test="<xsl:when test="ExprExpr11">"> … … </xsl:when></xsl:when>

<xsl:when test="<xsl:when test="ExprExpr22">"> … … </xsl:when></xsl:when>… …

<!-- If no '<!-- If no 'whenwhen' applies, an optional ' applies, an optional ''otherwiseotherwise' is instantiated: -->' is instantiated: --><xsl:otherwise><xsl:otherwise> … … </xsl:otherwise></xsl:otherwise>

</xsl:choose></xsl:choose>

Page 20: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 20

Example (cont; Eliminating duplicate names)Example (cont; Eliminating duplicate names)

Only the Only the current()current() node accessible in current node list node accessible in current node list– but can refer to nodes in the but can refer to nodes in the source treesource tree– Process just the first one of duplicate Process just the first one of duplicate namenames: s: <xsl:for-each select="//name"><xsl:for-each select="//name"> <xsl:sort select="last"/><xsl:sort select="last"/><xsl:sort select="first" /> <xsl:sort select="first" /> <xsl:if test="not(<xsl:if test="not(

preceding::name[first=current()/first preceding::name[first=current()/first and and

last=current()/last] )">last=current()/last] )"> <LI><xsl:value-of select="last" <LI><xsl:value-of select="last" />, <xsl:value-of select="first"/></LI> />, <xsl:value-of select="first"/></LI></xsl:if></xsl:if>

</xsl:for-each></xsl:for-each>

Page 21: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 21

Numbering Document ContentsNumbering Document Contents

Formatted numbers can be generated using Formatted numbers can be generated using <<xsl:number xsl:number />/> – by the position of the current node in the source treeby the position of the current node in the source tree

» or by an explicit or by an explicit valuevalue="="ArithmEArithmExprxpr""

– nodes to be counted specified by a nodes to be counted specified by a countcount pattern pattern– supports common numbering schemes : single-level, supports common numbering schemes : single-level,

hierarchical, and sequential through levelshierarchical, and sequential through levels

Typical cases in following examplesTypical cases in following examples» (Complete specification is rather complex)(Complete specification is rather complex)

Example 1: Numbering list itemsExample 1: Numbering list items

Page 22: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 22

Generating numbers: Example 1Generating numbers: Example 1

<xsl:template match="ol/item"><xsl:template match="ol/item"> <!-- default: count similar <!-- default: count similar siblingssiblings (items) --> (items) --> <xsl:number format="1. "/><xsl:number format="1. "/> <xsl:apply-templates/> <xsl:apply-templates/><xsl:template><xsl:template>

itemitem itemitem itemitem

olol

apricotapricot bananabanana coconutcoconut

1.1. 2.2. 3.3.

apricotapricotbananabananacoconutcoconut

Page 23: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 23

Generating numbers: Example 2Generating numbers: Example 2

Hierarchical numbering (1, 1.1, 1.1.1, 1.1.2, …) Hierarchical numbering (1, 1.1, 1.1.1, 1.1.2, …) for titles of chapters, titles of their sections, and for titles of chapters, titles of their sections, and titles of subsections:titles of subsections:<xsl:template match="title"><xsl:template match="title"> <xsl:number level="multiple"<xsl:number level="multiple" count="chap | sect | subsect" count="chap | sect | subsect" format="1.1 "/> format="1.1 "/> <xsl:apply-templates/> <xsl:apply-templates/></xsl:template></xsl:template>

Page 24: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 24

Generating numbers: Example 2Generating numbers: Example 2

11 1.11.1 1.1.11.1.1 22

chapchap

SweetsSweets

titletitle

titletitle

BerriesBerries

sectsect

subsectsubsect

CherryCherry

titletitle

chapchap

titletitle

VegetablesVegetables

. . .. . .

. . .. . .

SweetsSweets BerriesBerries CherryCherry VegetablesVegetables

partpart

Page 25: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 25

Example 2: VariationExample 2: Variation

As above, but number titles within appendices As above, but number titles within appendices with A, A.1, A.1.1, B.1 etc:with A, A.1, A.1.1, B.1 etc:

<xsl:template match="appendix//title"><xsl:template match="appendix//title"> <xsl:number level="multiple" <xsl:number level="multiple" count="appendix | sect | subsect" count="appendix | sect | subsect" format="A.1 "/> format="A.1 "/> <xsl:apply-templates/> <xsl:apply-templates/></xsl:template></xsl:template>

Page 26: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 26

Example 2: VariationExample 2: Variation

AA A.1A.1 A.1.1A.1.1 BB

appendixappendix

SweetsSweets

titletitle

titletitle

BerriesBerries

sectsect

subsectsubsect

CherryCherry

titletitle

titletitle

VegetablesVegetables

. . .. . .

. . .. . .

SweetsSweets BerriesBerries CherryCherry VegetablesVegetables

appendixappendix

partpart

Page 27: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 27

Generating numbers: Example 3Generating numbers: Example 3

Sequential numbering of notesSequential numbering of notes withinwithin chapterschapters::(more precisely: starting anew at the start of any chapter)(more precisely: starting anew at the start of any chapter)

<xsl:template match="note"><xsl:template match="note"> <xsl:number level="any" <xsl:number level="any" from="chap" from="chap" format="(1) "/> format="(1) "/> <xsl:apply-templates/> <xsl:apply-templates/></xsl:template></xsl:template>

Page 28: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 28

Ex 3: Sequential numbering Ex 3: Sequential numbering fromfrom chap chap

chapchap

Yes!Yes!

notenote

notenote

No!No!

sectsectPerhaps?Perhaps?

notenotenotenote

OKOK

. . .. . .

. . .. . .(1)(1) (2)(2) (3)(3) (1)(1)

Yes!Yes! No!No! Perhaps?Perhaps? OKOK

chapchap

Page 29: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 29

4.2 Computing with XSLT4.2 Computing with XSLT

XSLT is a declarative rule-based languageXSLT is a declarative rule-based language– for XML transformationsfor XML transformations– Could we use it for general computing?Could we use it for general computing?– What is the exact computational power of XSLT?What is the exact computational power of XSLT?

We've seen some programming-like features:We've seen some programming-like features:– iteration over source nodes (iteration over source nodes (xsl:xsl:for-eachfor-each))

» XSLT 2.0 supports iteration over arbitrary sequencesXSLT 2.0 supports iteration over arbitrary sequences

– conditional evaluation (conditional evaluation (xsl:xsl:ifif andand xsl: xsl:choosechoose))

Page 30: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 30

Computing with XSLTComputing with XSLT

Further programming-like features:Further programming-like features:– variablesvariables (names bound to (names bound to non-updatablenon-updatable values): values): <xsl:for-each select="//name"><xsl:for-each select="//name"> <xsl:variable name="LAndF" <xsl:variable name="LAndF"

select="concat(last, ', ', first)"select="concat(last, ', ', first)" />/> ......

... ...</xsl:for-each></xsl:for-each>

– callablecallable named templatesnamed templates withwith parametersparameters:: <xsl:call-template name="process-name"><xsl:call-template name="process-name">

<xsl:with-param name="pname" <xsl:with-param name="pname" select="$LAndF" />select="$LAndF" /> </xsl:call-template> </xsl:call-template>

Page 31: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 31

Result Tree FragmentsResult Tree Fragments

Result tree fragmentsResult tree fragments built by templates can be stored, too: built by templates can be stored, too:

<xsl:variable name="fooBar"><xsl:variable name="fooBar"><FOO>BAR</FOO><FOO>BAR</FOO>

</xsl:variable></xsl:variable> They can only be used as string valuesThey can only be used as string values

substring($fooBar, 2, 2) = "AR"substring($fooBar, 2, 2) = "AR" or inserted in the result:or inserted in the result:

<xsl:copy-of select="$fooBar" /><xsl:copy-of select="$fooBar" />

(XSLT 2.0 allows unlimited accessing of (computed) (XSLT 2.0 allows unlimited accessing of (computed) sequences, e.g., with location paths)sequences, e.g., with location paths)

Page 32: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 32

Visibility of Variable BindingsVisibility of Variable Bindings

The binding is The binding is visiblevisible in following siblings of in following siblings of xsl:variable,xsl:variable, and in their descendants:and in their descendants:

<xsl:for-each select="//name"><xsl:for-each select="//name"> <xsl:variable name="LAndF" <xsl:variable name="LAndF"

select="concat(last, ', ', first)"select="concat(last, ', ', first)" />/> ... ... <xsl:call-template name="process-name"> <xsl:call-template name="process-name">

<xsl:with-param name="pname" <xsl:with-param name="pname" select="$LAndF" />select="$LAndF" /> </xsl:call-template> </xsl:call-template>

... ...

</xsl:for-each></xsl:for-each><TABLE> . . . </TABLE><TABLE> . . . </TABLE>

Page 33: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 33

A Real-Life ExampleA Real-Life Example

We used LaTeX to format an XML article. For this, we We used LaTeX to format an XML article. For this, we needed to map source table structuresneeded to map source table structures

<tgroup cols="3"><tgroup cols="3">......

</tgroup> </tgroup>to corresponding LaTeX environments:to corresponding LaTeX environments:

\begin{tabular}{lll} %3 left-justified \begin{tabular}{lll} %3 left-justified colscols

... ... \end{tabular}\end{tabular}

How to do this? How to do this?

Page 34: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 34

Possible solution (for up to 4 columns)Possible solution (for up to 4 columns)

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

\begin{tabular}{l\begin{tabular}{l

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

\end{tabular}\end{tabular}

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

OK, but inelegant!OK, but inelegant! How to support arbitrarily many columns?How to support arbitrarily many columns?

<xsl:if test="@cols > 1"><xsl:if test="@cols > 1">ll</xsl:if</xsl:if ><xsl:if test="@cols > 2">><xsl:if test="@cols > 2">ll</xsl:if</xsl:if ><xsl:if test="@cols > 3">><xsl:if test="@cols > 3">ll</xsl:if></xsl:if>

Page 35: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 35

More General Solution (1/2)More General Solution (1/2)

Pass the column-count to a named template which Pass the column-count to a named template which generates the requested number of ‘generates the requested number of ‘ll’s:’s:

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

\begin{tabular}{\begin{tabular}{

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

\end{tabular}\end{tabular}

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

<xsl:call-template name="gen-cols"><xsl:call-template name="gen-cols"> <xsl:with-param name="count" select="<xsl:with-param name="count" select="@cols@cols" />" /> <xsl:with-param name="symb" select="<xsl:with-param name="symb" select="'l''l'" />" /> </xsl:call-template></xsl:call-template>

Page 36: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 36

Solution 2/2: Recursive Solution 2/2: Recursive gen-colsgen-cols

<xsl:template name="gen-cols"><xsl:template name="gen-cols">

<xsl:param name="count" /><xsl:param name="count" />

<xsl:param name="symb" /><xsl:param name="symb" />

<xsl:if test="$count > 0"><xsl:if test="$count > 0"><xsl:value-of select="$symb" /><xsl:value-of select="$symb" /><xsl:call-template name="gen-cols"><xsl:call-template name="gen-cols">

<xsl:with-param name="count" <xsl:with-param name="count" select="$count - 1" />select="$count - 1" />

<xsl:with-param name="symb" <xsl:with-param name="symb" select="$symb" />select="$symb" />

</xsl:call-template></xsl:call-template>

</xsl:if></xsl:if>

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

formal parametersformal parameters

Page 37: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 37

Iteration in XSLT 2.0Iteration in XSLT 2.0

XSLT 2.0 is more convenient, by allowing iteration over XSLT 2.0 is more convenient, by allowing iteration over generated sequencesgenerated sequences, too:, too:

<xsl2:template match="tgroup"><xsl2:template match="tgroup"> \\begin{tabular}{begin{tabular}{<xsl2:for-each <xsl2:for-each

select="select="1 to @cols1 to @cols">">

<xsl2:text><xsl2:text>ll</xsl2:text></xsl2:text>

</xsl2:for-each></xsl2:for-each>}}

\end{tabular}\end{tabular}

</xsl2:template></xsl2:template>

Page 38: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 38

Stylesheet ParametersStylesheet Parameters

Stylesheet can get params from command line, or through Stylesheet can get params from command line, or through JAXP with JAXP with

Transformer.setParameter(name, value)Transformer.setParameter(name, value) ::<xsl:transform ... ><xsl:transform ... >

<xsl:output method="text" /><xsl:output method="text" />

<xsl:param name="In" select="0" /><xsl:param name="In" select="0" /> <xsl:template match="/"><xsl:template match="/">

<xsl:value-of select="2*<xsl:value-of select="2*$In$In"/> </xsl:template>"/> </xsl:template>

</xsl:transform></xsl:transform>

$ java -jar saxon.jar dummy.xml double.xslt In=120$ java -jar saxon.jar dummy.xml double.xslt In=120

240240

default valuedefault value

Page 39: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 39

Generating XML Test CasesGenerating XML Test Cases

XSLT is handy for generating XML test casesXSLT is handy for generating XML test cases An XSLT 2.0 script to generate An XSLT 2.0 script to generate nn sections: sections:

<!DOCTYPE xsl:transform [ <!DOCTYPE xsl:transform [

<!ENTITY CONT "<xsl:comment>Lengthy XML fragment <!ENTITY CONT "<xsl:comment>Lengthy XML fragment (excluded)</xsl:comment>" > (excluded)</xsl:comment>" >

]>]>

<xsl:transform version="2.0" <xsl:transform version="2.0"

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

<xsl:param name="n" select="10"/><xsl:param name="n" select="10"/>

Page 40: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 40

XSLT 2.0 script continuesXSLT 2.0 script continues

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

<doc> <title>A doc with <xsl:value-of select="$n"/> <doc> <title>A doc with <xsl:value-of select="$n"/> sections</title>sections</title>

<xsl:for-each select="1 to $n"><xsl:for-each select="1 to $n">

<section> <title>Section number <xsl:value-of <section> <title>Section number <xsl:value-of select="." /> </title>select="." /> </title>

&CONT;&CONT; </section> </section> </xsl:for-each> </xsl:for-each> </doc></doc>

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

</xsl:transform></xsl:transform>

Extensions in XPath 2.0,Extensions in XPath 2.0, to generate and access to generate and access non-node sequencesnon-node sequences

Page 41: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 41

Invoking the ScriptInvoking the Script

The script can be used as the required (dummy) input The script can be used as the required (dummy) input document: document:

$ saxon9 genTest-iter.xslt genTest-iter.xslt n=1000$ saxon9 genTest-iter.xslt genTest-iter.xslt n=1000

XSLT 1.0 does not support iteration over generated XSLT 1.0 does not support iteration over generated sequences ; In XSLT 1.0 we must recurse:sequences ; In XSLT 1.0 we must recurse:

<doc> <title>A doc with <xsl:value-of select="$n"/> <doc> <title>A doc with <xsl:value-of select="$n"/> sections</title>sections</title>

<xsl:call-template name ="genSecs"><xsl:call-template name ="genSecs">

<xsl:with-param name="count" select="1"/><xsl:with-param name="count" select="1"/>

</xsl:call-template></xsl:call-template>

</doc></doc>

Page 42: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 42

Tail-recursive Tail-recursive genSecsgenSecs template template

<xsl:template name="genSecs"><xsl:template name="genSecs"> <xsl:param name="count" /><xsl:param name="count" /> <xsl:if test="$count &lt;= $n"><xsl:if test="$count &lt;= $n"> <section><title>Section <xsl:value-of <section><title>Section <xsl:value-of

select="$count"/></title>select="$count"/></title> &CONT;&CONT;

</section> </section> <!-- Create the rest sections: --><!-- Create the rest sections: --> <xsl:call-template name="genSecs"><xsl:call-template name="genSecs"> <xsl:with-param name="count" <xsl:with-param name="count"

select="$count + 1" />select="$count + 1" /> </xsl:call-template></xsl:call-template> </xsl:if></xsl:if></xsl:template></xsl:template>

Page 43: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2008SDPL 2008 4343

Problem with Tail-RecursionProblem with Tail-Recursion

The depth of tail-recursion is linear. This may lead The depth of tail-recursion is linear. This may lead to problems with large to problems with large nn (say, above a few (say, above a few thousands):thousands): Saxon:Saxon: StackOverflowError StackOverflowError xsltproc: xsltproc: "A potential infinite template recursion was "A potential infinite template recursion was

detected. You can adjust xsltMaxDepth (--maxdepth) in detected. You can adjust xsltMaxDepth (--maxdepth) in order to raise the maximum number of nested template order to raise the maximum number of nested template calls and variables/params (currently set to 3000)."calls and variables/params (currently set to 3000)."

Solution: Enter Algorithm Design!Solution: Enter Algorithm Design!

SDPL 2011 43XSLT: Additional features & Computing

Page 44: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2008SDPL 2008 4444

Apply Divide-and-ConquerApply Divide-and-Conquer

Split the problem/task in (equal-sized) sub-Split the problem/task in (equal-sized) sub-problems, and solve them recursivelyproblems, and solve them recursively

To generate secs To generate secs $first$first, ..., , ..., $last$last, compute their, compute their mid-point mid-point $mid$mid, and generate the halves , and generate the halves $first$first, ..., , ..., $mid$mid, , and and $mid+1$mid+1, ..., , ..., $last$last::

<xsl:call-template name="genSecsDC"><xsl:call-template name="genSecsDC"> <xsl:with-param name="<xsl:with-param name="firstfirst" select="1"/>" select="1"/> <xsl:with-param name="<xsl:with-param name="lastlast" select="$n"/>" select="$n"/> </xsl:call-template></xsl:call-template>

SDPL 2011 44XSLT: Additional features & Computing

Page 45: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2008SDPL 2008 4545

Divide-and-ConquerDivide-and-Conquer genSecs genSecs template template

<xsl:template name="genSecsDC"><xsl:template name="genSecsDC"> <xsl:param name="first" /><xsl:param name="first" /> <xsl:param name="last" /><xsl:param name="last" /> <xsl:choose><xsl:choose> <xsl:when test="$first = $last"><xsl:when test="$first = $last"> <!-- base case --> <!-- base case --> <section> <section> <title>Section number <title>Section number

<xsl:value-of select="$first"/></title> <xsl:value-of select="$first"/></title> &CONT;&CONT; </section></section> </xsl:when></xsl:when> <!-- otherwise recurse: --> <!-- otherwise recurse: -->

SDPL 2011 45XSLT: Additional features & Computing

Page 46: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2008SDPL 2008 4646

Divide&ConquerDivide&Conquer genSecs genSecs (cont.) (cont.)

<xsl:when test="$first &lt; $last"><xsl:when test="$first &lt; $last"> <xsl:variable name="mid" <xsl:variable name="mid"

select="floor(($first + $last) div 2)" /> select="floor(($first + $last) div 2)" /> <xsl:call-template name="genSecsDC"><xsl:call-template name="genSecsDC"> <xsl:with-param name="first" select="$first" /><xsl:with-param name="first" select="$first" /> <xsl:with-param name="last" select="$mid" /><xsl:with-param name="last" select="$mid" /> </xsl:call-template></xsl:call-template> <xsl:call-template name="genSecsDC"><xsl:call-template name="genSecsDC"> <xsl:with-param name="first" select="$mid+1" /><xsl:with-param name="first" select="$mid+1" /> <xsl:with-param name="last" select="$last" /><xsl:with-param name="last" select="$last" /> </xsl:call-template></xsl:call-template> </xsl:when></xsl:when> </xsl:choose></xsl:choose></xsl:template></xsl:template>

SDPL 2011 46XSLT: Additional features & Computing

Page 47: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2008SDPL 2008 4747

Balanced D&C Recursion Tree (draw it!)Balanced D&C Recursion Tree (draw it!)

SDPL 2011 47XSLT: Additional features & Computing

Page 48: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2008SDPL 2008 4848

Effect of Divide-and-ConquerEffect of Divide-and-Conquer

The depth of balanced divide-and-conquer The depth of balanced divide-and-conquer recursion is recursion is logarithmiclogarithmic only only E.g., log(10^6) ~ 20, log(10^9) ~ 30E.g., log(10^6) ~ 20, log(10^9) ~ 30 Piece of cake!Piece of cake!

Divide-and-conquer doubles the number of Divide-and-conquer doubles the number of recursive calls above. Does this make a big recursive calls above. Does this make a big difference? difference?

No; See nextNo; See next

SDPL 2011 48XSLT: Additional features & Computing

Page 49: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2008SDPL 2008 4949

XSLT 1.0 execution timesXSLT 1.0 execution times

$ time saxon genTest-tailrec.xslt genTest-$ time saxon genTest-tailrec.xslt genTest-tailrectailrec.xslt .xslt n=1000000 > /dev/nulln=1000000 > /dev/null

realreal 0m12.808s0m12.808suseruser 0m12.924s0m12.924ssyssys 0m0.104s0m0.104s

$ time saxon genTest-tailrec.xslt genTest-$ time saxon genTest-tailrec.xslt genTest-dcdc.xslt .xslt n=1000000 > /dev/nulln=1000000 > /dev/null

realreal 0m13.871s 0m13.871s (~8% more)(~8% more)useruser 0m14.016s0m14.016ssyssys 0m0.088s0m0.088s

SDPL 2011 49XSLT: Additional features & Computing

Div&Conquer scriptDiv&Conquer script

Page 50: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2008SDPL 2008 5050

Iteration vs Tail-recursion vs Div&ConqIteration vs Tail-recursion vs Div&Conq

Some XSLT 2.0 execution times:Some XSLT 2.0 execution times:

$ time saxon9 dummy.xml genTest-$ time saxon9 dummy.xml genTest-iteriter.xslt n=1000000.xslt n=1000000realreal 0m11.277s0m11.277suseruser 0m10.118s0m10.118s

$ time saxon9 dummy.xml genTest-$ time saxon9 dummy.xml genTest-tailrectailrec.xslt n=1000000.xslt n=1000000realreal 0m24.803s 0m24.803s (~120% more than iteratively)(~120% more than iteratively)useruser 0m24.658s0m24.658s

$ time saxon9 dummy.xml genTest-$ time saxon9 dummy.xml genTest-dcdc.xslt n=1000000.xslt n=1000000realreal 0m29.779s 0m29.779s (~164% more than iteratively)(~164% more than iteratively)useruser 0m30.178s0m30.178s

SDPL 2011 50XSLT: Additional features & Computing

Page 51: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2008SDPL 2008 5151

Simulating DB QueriesSimulating DB Queries

Relational DB queries can be simulated easily, Relational DB queries can be simulated easily, with variables and nested with variables and nested for-eachfor-each loops loops– (but XQuery is more suitable for such)(but XQuery is more suitable for such)

Example: Example: – Join ”tuples” by matching values of their fieldsJoin ”tuples” by matching values of their fields– Assume information of fathers' addresses and Assume information of fathers' addresses and

children:children:

SDPL 2011 51XSLT: Additional features & Computing

Page 52: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2008SDPL 2008 5252

Example ”database”Example ”database”

Contents of the input document:Contents of the input document:

<daddies><daddies> <dad name="Pekka" addr="Stake way 6" /><dad name="Pekka" addr="Stake way 6" /> <dad name="Paavo" addr="Hey road 13" /> <dad name="Paavo" addr="Hey road 13" /></daddies></daddies><children><children> <child name="Aino" daddy="Pekka" /> <child name="Aino" daddy="Pekka" /> <child name="Helmi" daddy="Pekka" /> <child name="Helmi" daddy="Pekka" /> <child name="Onni" daddy="Pekka" /> <child name="Onni" daddy="Pekka" /> <child name="Pipsa" daddy="Paavo" /> <child name="Pipsa" daddy="Paavo" /></children></children>

SDPL 2011 52XSLT: Additional features & Computing

Page 53: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2008SDPL 2008 5353

Requested ResultRequested Result

Children joined with their (daddies') addresses:Children joined with their (daddies') addresses:

<ChildrensAddrs><ChildrensAddrs> <childAddr name="Aino" addr="Stake way 6" /> <childAddr name="Aino" addr="Stake way 6" /> <childAddr name="Helmi" addr="Stake way 6" /> <childAddr name="Helmi" addr="Stake way 6" /> <childAddr name="Onni" addr="Stake way 6" /> <childAddr name="Onni" addr="Stake way 6" /> <childAddr name="Pipsa" addr="Hey road 13" /> <childAddr name="Pipsa" addr="Hey road 13" /></ChildrensAddrs></ChildrensAddrs>

SDPL 2011 53XSLT: Additional features & Computing

Page 54: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2008SDPL 2008 5454

SolutionSolution

Join children with their daddies:Join children with their daddies:<xsl:template match="/"><xsl:template match="/"> <ChildrensAddrs><ChildrensAddrs> <xsl:for-each select="//daddies/dad"> <xsl:for-each select="//daddies/dad"> <xsl:variable name="D" select="." /> <xsl:variable name="D" select="." /> <xsl:for-each <xsl:for-each

select="//children/child[@daddy = select="//children/child[@daddy = $D/@name]">$D/@name]"> <childAddr <childAddr name="name="{@name}{@name}""

addr="addr="{$D/@addr}{$D/@addr}"" />/> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:for-each> </ChildrensAddrs></ChildrensAddrs></xsl:template></xsl:template>

SDPL 2011 54XSLT: Additional features & Computing

Page 55: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 55

Computational Power of XSLTComputational Power of XSLT

XSLT seems quite powerful, but how powerful is it?XSLT seems quite powerful, but how powerful is it?– Implementations provide extension mechanisms, e.g., to Implementations provide extension mechanisms, e.g., to

call arbitrary Java methodscall arbitrary Java methods– Are there limits to XSLT processing that we can do Are there limits to XSLT processing that we can do

without extensions?without extensions?

We’ll see that We’ll see that anyany algorithmic computation can be algorithmic computation can be simulated with plain XSLTsimulated with plain XSLT– shown indirectly, through simulating Turing machines by shown indirectly, through simulating Turing machines by

XSLTXSLT

Page 56: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 56

Turing MachineTuring Machine

Alan Turing 1936/37Alan Turing 1936/37 formal model of algorithmsformal model of algorithms primitive but powerful enough to simulate any primitive but powerful enough to simulate any

computation expressible in any algorithmic model computation expressible in any algorithmic model ((Church/Turing thesisChurch/Turing thesis))

Turing machineTuring machine– A finite set of A finite set of statesstates– unlimited unlimited tapetape of cells for symbols, examined by a tape of cells for symbols, examined by a tape

headhead

Page 57: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 57

Illustration of a Turing MachineIllustration of a Turing Machine

00 11 00001111 11

state-basedstate-basedcontrolcontrol

Page 58: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 58

Control of a Turing machineControl of a Turing machine

Control defined by a Control defined by a transition functiontransition function ((qq, , aa) = () = (q´q´, , b, db, d), where ), where dd {left, right} {left, right}– Meaning: with current state Meaning: with current state qq and tape symbol and tape symbol a,a,

» move to new state move to new state q´q´» replace symbol replace symbol aa in the current cell by ‘ in the current cell by ‘bb’’» move tape-head one step in direction move tape-head one step in direction dd

Such control can be simulated in XSLT with a Such control can be simulated in XSLT with a recursive named-template; Call it recursive named-template; Call it transitiontransition

Page 59: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 59

TM for recognizing {a,b} palindromesTM for recognizing {a,b} palindromes

markmark

move_amove_a

move_bmove_b test_btest_b

test_atest_a

YESYES NONO returnreturn

a/#, Ra/#, R

a/a, Ra/a, Rb/b, Rb/b, R

b/#, Rb/#, R

a/a, Ra/a, Rb/b, Rb/b, R

#/#, L#/#, L

#/#, L#/#, L

#/#, L#/#, L

#/#, L#/#, L

#/#, L#/#, L

b/b, Lb/b, L

a/a, La/a, L

a/#, La/#, L

b/#, Lb/#, L

a/a, La/a, Lb/b, Lb/b, L

#/#, R#/#, R

Page 60: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 60

The “The “transitiontransition” template” template

Parameters:Parameters:– statestate: the current state: the current state– leftleft: contents of the tape up to the tape head: contents of the tape up to the tape head– rightright: contents of the tape starting at the cell : contents of the tape starting at the cell

pointed by the tape headpointed by the tape head Template Template transitiontransition simulates a single simulates a single

transition step; calls itself with updated transition step; calls itself with updated parametersparameters

Page 61: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 61

Overall structure of TM simulationOverall structure of TM simulation

<xsl:template name="transition"><xsl:template name="transition"><!-- params and trace output omitted --><!-- params and trace output omitted --><xsl:choose><xsl:choose><xsl:when test="$state='YES'"><xsl:when test="$state='YES'">

<ACCEPT /> </xsl:when><ACCEPT /> </xsl:when><!-- xsl:when for each move ... --><!-- xsl:when for each move ... -->

<xsl:otherwise> <xsl:otherwise> <REJECT /> </xsl:otherwise><REJECT /> </xsl:otherwise>

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

Page 62: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 62

Updating the TM tape representationUpdating the TM tape representation

For each For each rightright-move -move ((qq, , aa) = () = (q´q´, , bb, right), , right), concatenate concatenate ''bb'' at the end of at the end of $$leftleft and drop and drop the first character of the first character of $$rightright

LeftLeft-moves -moves ((qq11, , aa) = () = (qq22, , bb, left) in a similar , left) in a similar

manner: manner: – drop the last character of drop the last character of $left$left, , and concatenate it and concatenate it

in front of in front of $right$right whose first character has been whose first character has been replaced by 'b'replaced by 'b'

Example: a TM for palindromes over alphabet Example: a TM for palindromes over alphabet {a, b}; ('#' used for denoting empty cells){a, b}; ('#' used for denoting empty cells)

Page 63: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 63

Simulating a single step (1/2)Simulating a single step (1/2)

<!-- sigma(mark,a) = (move_a,#,right): --><!-- sigma(mark,a) = (move_a,#,right): -->

<xsl:when test="$state='mark' and <xsl:when test="$state='mark' and starts-with($right, 'a')"> starts-with($right, 'a')">

<!-- First update the parameters: --> <!-- First update the parameters: --> <xsl:variable name="newstate" <xsl:variable name="newstate"

select="'move_a'"/> select="'move_a'"/> <xsl:variable name="newleft" <xsl:variable name="newleft"

select="concat($left, '#')"/> select="concat($left, '#')"/> <xsl:variable name="newright" <xsl:variable name="newright"

select="substring($right, 2)"/> select="substring($right, 2)"/>

Page 64: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 64

Simulating a single step (2/2)Simulating a single step (2/2)

<!-- Then call "transition" with new params: --><!-- Then call "transition" with new params: -->

<xsl:call-template name="transition"><xsl:call-template name="transition">

<xsl:with-param name="state" <xsl:with-param name="state" select="$newstate"/>select="$newstate"/>

<xsl:with-param name="left" <xsl:with-param name="left" select= "$newleft"/>select= "$newleft"/>

<xsl:with-param name = "right" <xsl:with-param name = "right" select="$newright"/>select="$newright"/>

</xsl:call-template></xsl:call-template>

</xsl:when></xsl:when>

Page 65: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 65

Sample trace of TM simulationSample trace of TM simulation

$ saxon dummy.xml tm-palindr.xsl input-tape=aba$ saxon dummy.xml tm-palindr.xsl input-tape=aba<M state="#[mark]aba#"/><M state="#[mark]aba#"/><M state="##[move_a]ba#"/><M state="##[move_a]ba#"/><M state="##b[move_a]a#"/><M state="##b[move_a]a#"/><M state="##ba[move_a]#"/><M state="##ba[move_a]#"/><M state="##b[test_a]a#"/><M state="##b[test_a]a#"/><M state="##[return]b##"/><M state="##[return]b##"/><M state="#[return]#b##"/><M state="#[return]#b##"/><M state="##[mark]b##"/><M state="##[mark]b##"/><M state="###[move_b]##"/><M state="###[move_b]##"/><M state="##[test_b]###"/><M state="##[test_b]###"/><M state="#[YES]####"/><M state="#[YES]####"/><ACCEPT/><ACCEPT/>

state shown asstate shown astape-lefttape-left[[statestate]]tape-righttape-right

Page 66: SDPL 2011XSLT: Additional features & Computing1 4.1 Additional XSLT Features n XPath for arithmetics, cross-references, and string manipulation n Generating

SDPL 2011 XSLT: Additional features & Computing 66

Implications of TM simulationImplications of TM simulation

XSLT has XSLT has full algorithmic powerfull algorithmic power– It is "Turing-complete"It is "Turing-complete"– Is this intentional?Is this intentional?

» Not a general-purpose programming language!Not a general-purpose programming language!

– Impossible to recognise non-terminating Impossible to recognise non-terminating transformations automatically transformations automatically (( the "halting problem" has no algorithmic solution) the "halting problem" has no algorithmic solution)

» Could try denial-of-service attacks through non-Could try denial-of-service attacks through non-terminating style sheetsterminating style sheets