SDPL 2005 Notes 5.1: Additional XPath & XSLT 1
5.1 Additional features of XPath & XSLT5.1 Additional features of XPath & XSLT
XPath support forXPath support for– arithmeticsarithmetics– processing ID/IDREF cross-referencesprocessing ID/IDREF cross-references– manipulation of stringsmanipulation of strings
Generating textGenerating text– for contentfor content– for attribute valuesfor attribute values
Repetition, sorting and conditional processingRepetition, sorting and conditional processing Generating numbersGenerating numbers
SDPL 2005 Notes 5.1: Additional XPath & XSLT 2
XPath: Arithmetical OperationsXPath: Arithmetical Operations
Operators for double-precision (64 bit) floating-Operators for double-precision (64 bit) floating-point arithmeticspoint arithmetics
+, -, *, div, mod+, -, *, div, mod (same as (same as %% in Java)in Java)
Mapping numbers to integers:Mapping numbers to integers:» floor(x) = max{nfloor(x) = max{n n n x} x} » ceiling(x) = min{nceiling(x) = min{n n n x} x} » round(x) = floor(x+0.5) round(x) = floor(x+0.5)
Formatting numbers as strings (example):Formatting numbers as strings (example):» format-number(-1.2534, format-number(-1.2534, ""0.00.0"") = ) = ""-1.3-1.3""
SDPL 2005 Notes 5.1: Additional XPath & XSLT 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: – Grade average for the first student in document:Grade average for the first student in document:sum(sum((//student)[1]/course/@grade(//student)[1]/course/@grade)) div div count(count((//student)[1]/course(//student)[1]/course))
SDPL 2005 Notes 5.1: Additional XPath & XSLT 4
Cross-referencingCross-referencing
Function Function idid selects elements by their unique IDselects elements by their unique ID– NBNB: ID attributes need to be declared in DTD: ID attributes need to be declared in DTD
(See an example later)(See an example later)
Examples:Examples:– id('sect:intro')id('sect:intro')
selects the element with unique IDselects the element with unique ID "sect:intro""sect:intro"– id('sect:intro')/para[5]id('sect:intro')/para[5]
selects the fifthselects the fifth parapara child of the above elementchild of the above element– id('sect1 sect2 sect3')id('sect1 sect2 sect3')selects 3 sections selects 3 sections
(if they have the corresponding ID values)(if they have the corresponding ID values)
SDPL 2005 Notes 5.1: Additional XPath & XSLT 5
String manipulationString manipulation
Equality and inequality of strings can be tested Equality and inequality of strings can be tested with operatorswith operators == and and !=!=– "foo" = 'foo'"foo" = 'foo'; ; "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"
SDPL 2005 Notes 5.1: Additional XPath & XSLT 6
XPath: more string functionsXPath: more 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"– 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"
– string-length("dogbert")=7string-length("dogbert")=7– translate(translate(Str, Replaced, ReplacingStr, Replaced, Replacing):):
» translate("translate("doggdoggy","y","dgodgo","Ssi")="Sissy"","Ssi")="Sissy"
SDPL 2005 Notes 5.1: Additional XPath & XSLT 7
Generating TextGenerating Text
The string-value of an expression can be inserted in the The string-value of an expression can be inserted in the result tree by instructionresult tree by instruction
<<xsl:value-ofxsl:value-of select=" select="ExprExpr" />" />– if if ExprExpr evaluates to a node-set, evaluates to a node-set, value of the first nodevalue of the first node in in
document order is useddocument order is used
Consider transforming source elements likeConsider transforming source 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 ("Bird") ParkerCharlie ("Bird") Parker
SDPL 2005 Notes 5.1: Additional XPath & XSLT 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"><xls:value-of select="first" /><xls:value-of select="first" />("<xsl:value-of select="@alias" />") ("<xsl:value-of select="@alias" />") <xls:value-of select="last" /> <xls:value-of select="last" /> <xsl:text><xsl:text></xsl:text></xsl:text></xsl:template></xsl:template>
Verbatim text (like the white-space above) can be Verbatim text (like the white-space above) can be inserted usinginserted using xsl:text xsl:text
SDPL 2005 Notes 5.1: Additional XPath & XSLT 9
Attribute value templatesAttribute value templates
The string-value of an expression can be inserted The string-value of an expression can be inserted in an attribute value by surrounding the in an attribute value by surrounding the expression by bracesexpression by braces {{ and and }}
Consider transforming source elementConsider transforming 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" />
SDPL 2005 Notes 5.1: Additional XPath & XSLT 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} and and {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)
SDPL 2005 Notes 5.1: Additional XPath & XSLT 11
XSLT: RepetitionXSLT: Repetition
Nodes can be "pulled" from source for Nodes can be "pulled" from source for processing using processing using
<<xsl:xsl:for-eachfor-each select=" select="ExprExpr">">TemplateTemplate
<<xsl:xsl:for-eachfor-each>>
– the template is applied to each of the selected the template is applied to each of the selected nodes (0, 1 or more), each node in turn as the nodes (0, 1 or more), 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)
SDPL 2005 Notes 5.1: Additional XPath & XSLT 12
Example (of Example (of xsl:xsl:for-eachfor-each))
Consider formatting the below document as HTML:Consider formatting 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>
SDPL 2005 Notes 5.1: Additional XPath & XSLT 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:for-each select="//section/title"><xsl:for-each select="//section/title"> <LI><xsl:apply-templates /></LI> <LI><xsl:apply-templates /></LI> </xsl:for-each></xsl:for-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>
SDPL 2005 Notes 5.1: Additional XPath & XSLT 14
Example (cont; Cross references)Example (cont; Cross references)
Cross references (to sections) can also be processed Cross references (to sections) can also be processed using using xsl:for-each: xsl:for-each: <xsl:template match="title-ref"> <xsl:template match="title-ref"> <xsl:for-each select="id(@idref)"><xsl:for-each select="id(@idref)"> 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 …)
SDPL 2005 Notes 5.1: Additional XPath & XSLT 15
XSLT SortingXSLT Sorting
A sorted order for the processing of nodes with A sorted order for the processing of nodes with xsl:for-eachxsl:for-each and and xls:apply-templatesxls:apply-templates can be specified by can be specified by <<xsl:sortxsl:sort/>/>
controlled by attributes of controlled by attributes of xsl:sortxsl:sort like like– selectselect: expression for the sort key: expression for the sort key– 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.
SDPL 2005 Notes 5.1: Additional XPath & XSLT 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>
SDPL 2005 Notes 5.1: Additional XPath & XSLT 17
What about duplicates?What about duplicates?
Is it possible to eliminate duplicate values like Is it possible to eliminate duplicate values like <LI>Brown, Helen</LI> <LI>Brown, Helen</LI> <LI>Brown, Helen</LI> <LI>Brown, Helen</LI> ??
Yes (but not that straightforward)Yes (but not that straightforward) Using conditional instructionsUsing conditional instructions
– See nextSee next
SDPL 2005 Notes 5.1: Additional XPath & XSLT 18
Conditional processingConditional processing
A template can be instantiated or ignored based A template can be instantiated or ignored based on the value of a on the value of a testtest Boolean expression, usingBoolean expression, using
<<xsl:ifxsl:if test=" test="ExpressionExpression">">TemplateTemplate
</</xsl:ifxsl: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="position() < last()" test="position() < last()" > >, , </</xsl:ifxsl:if>></xsl:template></xsl:template>
SDPL 2005 Notes 5.1: Additional XPath & XSLT 19
Conditional processing (2)Conditional processing (2)
Also a case-like construct (Also a case-like 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 <xsl:when test="test="ExprExpr11"">> … … </xsl:when></xsl:when>
<xsl:when <xsl:when test="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>
SDPL 2005 Notes 5.1: Additional XPath & XSLT 20
Example (cont; Eliminating duplicate names)Example (cont; Eliminating duplicate names)
No access to other nodes (except No access to other nodes (except current()current()) in the list of ) in the list of xsl:for-eachxsl:for-each– But can refer to other nodes in the source treeBut can refer to other nodes in the source 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 last=current()/last] )">and 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>
SDPL 2005 Notes 5.1: Additional XPath & XSLT 21
Generating NumbersGenerating Numbers
Formatted numbers can be inserted in the result Formatted numbers can be inserted in the result tree by element tree by element xsl:numberxsl:number – number can be specified by attributenumber can be specified by attribute value="value="ExprExpr""– otherwise the number generated by the position of the otherwise the number generated by the position of the
current node in the source treecurrent node in the source tree
We’ll consider typical cases through examplesWe’ll consider typical cases through examples– The complete rules of the Spec are rather complexThe complete rules of the Spec are rather complex
Example 1: Numbering list itemsExample 1: Numbering list items
SDPL 2005 Notes 5.1: Additional XPath & XSLT 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:numberxsl:number format="1. "/> 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
SDPL 2005 Notes 5.1: Additional XPath & XSLT 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:numberxsl:number level="multiple" 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>
SDPL 2005 Notes 5.1: Additional XPath & XSLT 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
SDPL 2005 Notes 5.1: Additional XPath & XSLT 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:numberxsl:number level="multiple" 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>
SDPL 2005 Notes 5.1: Additional XPath & XSLT 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
SDPL 2005 Notes 5.1: Additional XPath & XSLT 27
Generating numbers: Example 3Generating numbers: Example 3
Sequential numbering of Sequential numbering of notenotes s withinwithin chapchaptersters::(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:numberxsl:number level="any" level="any" from="chap" from="chap" format="(1) "/> format="(1) "/> <xsl:apply-templates/> <xsl:apply-templates/></xsl:template></xsl:template>
SDPL 2005 Notes 5.1: Additional XPath & XSLT 28
Ex 3: Sequential numbering Ex 3: Sequential numbering fromfrom chaps chaps
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
Top Related