Pre-requisite topics
Friday 16th September 2022
Friday 16th September 2022
In XML processing terminology most of the components of the document are referred to as nodes.
Nodes are the fundamental primative datatypes in XML documents, and include:
node() node-test in XPathEntities are codes that allow you to substitute some predefined text in your XML document.
&;&
You can define entities using DTDs, but for now we will consider character entities
Character entities replace a single character. They are normally used when:
There are three types of character entity:
XML defines five entities:
<<>>''""&&These entities use the unicode code point in either Decimal or Hexadecimal notation.
The Entity name starts with #, followed by a decimal or equivalent hex number.
©
©
©
Hex numbers start with the letter x, as you can see.
In a UTF-8 encoded document, one of these entities is defined as being equivalent to the character it represents - don't expect these entities to be preserved!
Namespaces are used to avoid ambiguity between elements with the same name.
*and sometimes attributes
XML is commonly used to create mashup documents with elements from more than one source. Namespaces let us identify that source and solve problems of ambiguity when more than one source used share an element name.
We'll look at two sets of elements. The first is about companies and the second about people. We want to create a document with contains information about companies supplying us and the named contact at that company.
<company>
<name>Cheap Stationery Ltd</name>
<supplier.code>ABC123</supplier.code>
<phone.number>+44 1825 607100</phone.number>
</company>
<person>
<name>Anthony Salesman</name>
<phone.number>+44 1825 607123</phone.number>
</person>
<supplier>
<name>Cheap Stationery Ltd</name>
<supplier.code>ABC123</supplier.code>
<phone.number>+44 1825 607100</phone.number>
<name>Anthony Salesman</name>
<phone.number>+44 1825 607123</phone.number>
</supplier>
There's a couple of problems here!
The simplest way of defining a namespace is using the default namespace declaration xmlns:
<company xmlns="http://www.corbas.co.uk/ns/company">
<name>Cheap Stationery Ltd</name>
<supplier.code>ABC123</supplier.code>
<phone.number>+44 1825 607100</phone.number>
</company>
This declaration puts the element in the http://www.corbas.co.uk/ns/company namespace.
Unless it declares a new namespace, any contained element is also in this namespace.
The namespace declaration looks like an attribute, but it is not! This can sometimes cause difficulties with SGML technologies like DTDs, which will try to treat them as an attribute instead.
<supplier>
<name xmlns="http://www.corbas.co.uk/ns/company">Cheap Stationery Ltd</name>
<supplier.code xmlns="http://www.corbas.co.uk/ns/company">ABC123</supplier.code>
<phone.number xmlns="http://www.corbas.co.uk/ns/company">+44 1825 607100</phone.number>
<name xmlns="http://www.corbas.co.uk/ns/person">Anthony Salesman</name>
<phone.number xmlns="http://www.corbas.co.uk/ns/person">+44 1825 607123</phone.number>
</supplier>
Unless you have a document entirely in a single namespace, writing out all of those URLs will soon get tiresome!
Thankfully, we can also use namespace declarations that associate the URL with a prefix:
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns="http://www.idpf.org/2007/opf"/>
Declaring a prefixed namespace like this doesn't automatically put the element in question in the namespace: we have to put the prefix at the front of the element name using a colon:
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns="http://www.idpf.org/2007/opf">
<dc:title>Gullivers Travels</dc:title>
</metadata>
<supplier xmlns:person="http://www.corbas.co.uk/ns/person" xmlns:company="http://www.corbas.co.uk/ns/company">
<company:name>Cheap Stationery Ltd</company:name>
<company:supplier.code>ABC123</company:supplier.code>
<company:phone.number>+44 1825 607100</company:phone.number>
<person:name>Anthony Salesman</person:name>
<person:phone.number>+44 1825 607123</person:phone.number>
</supplier>
An XPath statement selects (or matches) content in an XML document. Each XPath statement is made up of one or more location steps separated by slashes.
An initial / at the start of an XPath statement represents the document node — the entire document. Statements that start at the root are known as absolute paths and those which start at the current node are known as relative paths.
| Statement | Action |
|---|---|
/book/chapter |
Returns a set of nodes containing all the chapter elements that
are direct children of the book element which is, itself, the
root element |
chapter |
All of the chapter nodes that are children of the current node. The current node is known as the context node |
chapter/section/para |
All of the para elements that are grandchildren of
chapter elements and children of section
elements where the chapter elements are children of the context
node |
<p>My organisation believes in <emphasis role="italic">synchronised</emphasis> third-generation projections. We need to get <emphasis role="bold">on-message</emphasis> about our four-dimensional <emphasis role="underline">monitored</emphasis> concepts.</p>
The string value of:
<p>My organisation believes in <emphasis role="italic">synchronised</emphasis> third-generation projections. We need to get <emphasis role="bold">on-message</emphasis> about our four-dimensional <emphasis role="underline">monitored</emphasis> concepts.</p>
is:
My organisation believes in synchronised third-generation projections. We need to get on-message about our four-dimensional monitored concepts.
Location Steps can contain three parts.
All our statements so far are just node tests
true()
chapter[section]
.//country[population > 275000]
.//country[starts-with(@name, 'A')]
Use predicates to control selection. It leads to simpler code.
Use the position() function to locate nodes by position. The following selects just the first paragraph
of each chapter.
chapter/para[position() = 1]
This can be abbreviated to:
chapter/para[1]
You can use the last() function to find the last member of a set
chapter/para[last()]
All of the normal maths operators you know work
x + yx * yx - yx div y*
NOTE THIS ONE! - we obviously can't use the step seperator /
andornot() is function
chapter[title or section]
chapter[not(title)]
The result of boolean operations is true() or false().
//chapter[title][para]
Sequences were introduced in XPath 2
Prior to this, XPath statements only returned Node Sets*.
It can be important to recognise the difference!
EVERYTHING in XPath, XQuery and XSLT can be thought of a sequence!
Or tree fragments in XSLT 1.0 - but let's not worry about those today
XPath 1 returns atomic values or node sets, which have the following properties:
Although awareness of the node's original document/axis position may be retained
As the name suggests, they are limited to nodes, i.e:
In contrast, sequences are:
<letters>
<letter>a</letter>
<letter>b</letter>
<letter>c</letter>
<letter>d</letter>
<letter>e</letter>
<letter>f</letter>
</letters>
string-join(/letters/letter, '-')
This produces
a-b-c-d-e-f
Consider:
<person>
<given>Tom</given>
<family>Hillman</family>
</person>
We can use a sequence to define a desired order:
/person/(family, given)
()let $x := (1, 2, (), 3) return ($x, 4, 5, 6)
Returns (1, 2, 3, 4, 5, 6)
Since sequences are ordered, we can use the position predicate, amongst others.
This can be particularly useful when defining fall back options:
(/person/name/given, /person/name/full, /person/name/string(), person/nickname)[1]
XPath 1 only allows you to compare atomic values
XPath 2 allows you to compare sequences, too!
WARNING: the comparators for sequences in XPath 2 use the same symbols as the atomic comparators in XPath 1
It is good practice to use the following operators, even though sequence comparisons will (normally) provide the same results:
eqneltgtlegeNote that these are the same as XPath 1 atomic comparators
=!=<> (or >)<=, >= (or >=)These evaluate to true if ANY term in one sequence satisfies the equivalent comparison in ANY term in the other.
WARNING: in particular, A != B is unlikely to do what you think it does! Consider using not(A = B) instead.
Are the following true or false?
1 < 24
1 lt 24
(1, 7, 9) > (2, 4, 12)
(1, 7, 9) gt (2, 4, 12)
'four' = ('two', 'fourteen', 4)
1 = (1, 7, 9)
1 != (1, 7, 9)
not(1 = (1, 7, 9))
Which of these will be best practice?
if
if (@date1 gt @date2) then @date1 else @date2
else clause is mandatory: however, you can use the empty sequence ().for expressions
for $x in //lineitems return $x/@price * $x/@quantity
for $x in //lineitems return @price * @quantity
let expressionslet expressions allow one or more variables to be bound:
let $x := doc('a.xml')/*, $y := $x//*
return $y[@value gt $x/@min]
toYou can create sequences of consecutive integers using the to keyword:
1 to 10
(: returns (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) :)
reverse(10 to 15)
(: returns (15, 14, 13, 12, 11, 10) :)
Sequences were introduced in XPath 2
Prior to this, XPath statements only returned Node Sets*.
It can be important to recognise the difference!
EVERYTHING in XPath, XQuery and XSLT can be thought of a sequence!
Or tree fragments in XSLT 1.0 - but let's not worry about those today
XPath 1 returns atomic values or node sets, which have the following properties:
Although awareness of the node's original document/axis position may be retained
As the name suggests, they are limited to nodes, i.e:
In contrast, sequences are:
<letters>
<letter>a</letter>
<letter>b</letter>
<letter>c</letter>
<letter>d</letter>
<letter>e</letter>
<letter>f</letter>
</letters>
string-join(/letters/letter, '-')
This produces
a-b-c-d-e-f
Consider:
<person>
<given>Tom</given>
<family>Hillman</family>
</person>
We can use a sequence to define a desired order:
/person/(family, given)
()let $x := (1, 2, (), 3) return ($x, 4, 5, 6)
Returns (1, 2, 3, 4, 5, 6)
Since sequences are ordered, we can use the position predicate, amongst others.
This can be particularly useful when defining fall back options:
(/person/name/given, /person/name/full, /person/name/string(), person/nickname)[1]
XPath 1 only allows you to compare atomic values
XPath 2 allows you to compare sequences, too!
WARNING: the comparators for sequences in XPath 2 use the same symbols as the atomic comparators in XPath 1
It is good practice to use the following operators, even though sequence comparisons will (normally) provide the same results:
eqneltgtlegeNote that these are the same as XPath 1 atomic comparators
=!=<> (or >)<=, >= (or >=)These evaluate to true if ANY term in one sequence satisfies the equivalent comparison in ANY term in the other.
WARNING: in particular, A != B is unlikely to do what you think it does! Consider using not(A = B) instead.
Are the following true or false?
1 < 24
1 lt 24
(1, 7, 9) > (2, 4, 12)
(1, 7, 9) gt (2, 4, 12)
'four' = ('two', 'fourteen', 4)
1 = (1, 7, 9)
1 != (1, 7, 9)
not(1 = (1, 7, 9))
Which of these will be best practice?
Data types for XML mix several types into a type heirarchy. These types include:
All of these types can be presented as sequences of types using quantifiers (+, ?, *).
* potentially including user defined types
Taken from §1.6.1 of W3C Recommendation "XPath and XQuery Functions and Operators 3.1"
document-node() |
The document node; i.e. the document itself |
element() |
Element nodes |
attribute() |
Attribute nodes |
text() |
Text nodes i.e. each contiguous block of text in an XML document |
comment() |
Comment nodes |
processing-instruction() |
Processing-Instruction nodes |
namespace-node() |
Namespaces |
These are the primitive types and their derivatives that will be familiar to most programmers; here are a selection:
Taken from §1.6.3 of W3C Recommendation "XPath and XQuery Functions and Operators 3.1"
XPath, XQuery and XSLT are all functional languages.
This means that functions are "first class citizens" of the type heirarchy, and can be passed as an argument, returned from a function, and assigned to variables on the same basis as other types.
Functions allow XPath to define other types, in particular:
Converting between data types can be acheived in two ways:
cast as expression takes a sequence and attempts to convert to the given type.
"2013-08-10" cast as xs:date
xs:date("2013-08-10")
Both of the lines above convert the string 2013-08-10 into an xs:date.
XPath provides two useful functions for testing types:
instance ofcastable as
5 instance of xs:integer (: :)
5 instance of xs:decimal (: :)
(5, 6) instance of xs:decimal (: :)
(5, 6) instance of xs:decimal+ (: :)
() instance of xs:string* (: :)
"2013-08-10" castable as xs:date (: :)
"20130810" castable as xs:date (: :)
Extensible Stylesheet Language Transformation
Originally designed to produce PDFs as part of XSL-FO
XSLT Transforms XML - changes it in some way. It can:
The fundamental components of a stylesheet are xsl:template elements. The
root of all XSLT files is the xsl:stylesheet element.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="foo">
<bar>
<xsl:apply-templates/>
</bar>
</template>
</xsl:stylesheet>
xsl:stylesheetxsl:stylesheet is the root element for all XSLT documents.version attribute must be "1.0", "2.0" (or "3.0" with some
engines)xsl:templateThe XSLT processor follows a basic algorithm*:
*OK, this is a gross over-simplification. But the principle is about right!
The built in templates do the following:
xsl:template elements may have a match attributematch attributes allow the developer to control processing for some set
of elements
<xsl:template match="postcode">
<postalcode><xsl:apply-templates/></postalcode>
</xsl:template>
match attribute can be arbitrarily complex.xsl:apply-templatesxsl:apply-templates causes processing to continue
<xsl:apply-templates select="node()"/>
<xsl:stylesheet version="3.0">
<xsl:template match="*">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="text()|@*">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="comment()|processing-instruction()"/>
</xsl:stylesheet>
roughly!
xsl:copyxsl:copy-ofxsl:copy makes a shallow copy of the context nodexsl:copy-of makes a deep copy of selected contentxsl:copy takes a shallow copy of the context node
<xsl:template match="*">
<xsl:copy>Copied Something!</xsl:copy>
</xsl:template>
<chapter>
<para>This is my paragraph.</para>
</chapter>
<chapter>Copied Something!</chapter>
xsl:copy-of allows you to select an arbitrary set of nodes
and copy them to the outputselect attribute like that of xsl:apply-templates is used
<xsl:template match="country">
<xsl:copy>
<xsl:copy-of select="gdp|population"/>
</xsl:copy>
</xsl:template>
<xsl:stylesheet version="1.0">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Note: this is a simplified identity and won't always work – it needs modes and we haven't talked about them yet.
<xsl:template match="para">
<para><text><xsl:apply-templates/></text></para>
</xsl:template>
xsl:value-ofxsl:value-of generates a text node using a (string) valueselect attribute
<xsl:template match="@id">
<xsl:value-of select="@id"/>
</xsl:template>
We have looked at:
xsl:for-each-group instruction.Two functions are available when working with groups
current-grouping-key is only available when using group-by
and group-adjacent
current-group() is available in any descendant of a
xsl:for-each-group statement.
The context node within a grouping statement is set to the first node of the current group.
@group-by
<xsl:template match="book" mode="footnotes">
<xsl:for-each-group group-by="ancestor::chapter/@id" select=".//footnote">
<footnote-group parent="{current-grouping-key()}">
<xsl:apply-template select="current-group()"/>
</footnote-group>
</xsl:for-each-group>
</xsl:template>
group-by is evaluated and the items are grouped on the result@group-adjacentgroup-adjacent creates groups of nodes where the grouping key is
the same (as previously)
<xsl:template match="*[li]">
<xsl:for-each-group group-adjacent="local-name()" select="node()">
<xsl:where-populated>
<ul>
<xsl:apply-templates select="current-group()[self::li]"/>
</ul>
</xsl:where-populated>
<xsl:on-empty>
<xsl:apply-templates select="current-group()"/>
</xsl:on-empty>
</xsl:for-each-group>
</xsl:template>
@group-starting-withgroup-starting-with creates groups based on XPath match
patterns.
<xsl:template match="body">
<xsl:for-each-group group-starting-with="h1" select="*">
<section>
<xsl:copy-of select="current-group()"/>
</section>
</xsl:for-each-group>
</xsl:template>
@group-ending-withgroup-ending-with also creates groups based on XPath match
patterns.
<xsl:template match="body">
<xsl:for-each-group group-ending-with="hr" select="*">
<section>
<xsl:copy-of select="current-group()"/>
</section>
</xsl:for-each-group>
</xsl:template>
xsl:key and the key() functionKeys are a way to do an optimised index of your content. This can speed up
complex XPath statements. The key below creates an index of all the items
with id attributes, keyed on their id
<xsl:key match="*" name="elements-with-id" use="@id"/>
We use a key via the key() function
<xsl:variable name="target" select="key('elements-with-id', @referenced-id)"/>
Keys can return sets of values if the keys are not unique.
xsl:variablexsl:variable is used to store information during processing. Unlike
a variable in a procedural programming language, it cannot change once set. Use variables
liberally as they make your code more readable
<xsl:template match="country">
<xsl:variable name="gdp-per-head" select="round(gdp div population)"/>
<h1><xsl:apply-templates select="@name"/></h1>
<p><em>GDP per head</em> <xsl:value-of select="$gdp-per-head"/></p>
</xsl:template>
Variables are defined by name and referred to using the name preceded by a $ sign
xsl:variable (cont.)There are two ways to set a variable:
select attribute
<xsl:variable name="current-title" select="/document/title"/>
<xsl:variable name="style">font-family: Arial, Helvetica; font-size: 19pt</xsl:variable>
xsl:param allows parameters to be passed to stylesheets.
<xsl:stylesheet>
<xsl:param name="document-title"/>
<xsl:template match="document">
<article>
<head>
<title><xsl:value-of select="$document-title"/></title>
</head>
<body>…</body>
</article>
</xsl:template>
</xsl:stylesheet>
Once defined a parameter is used just like a variable.
<xsl:stylesheet>
<xsl:param name="required-class" select="'default-class'"/>
<xsl:param name="required-class">default-class</xsl:param>
</xsl:stylesheet>
Note the quotes around the value of the first - this specifies a string value rather than an XPath statement.
xsl:paramxsl:with-paramxsl:param allows parameters to stylesheets and templates to be defined with
optional default values. xsl:with-param passes parameters to templates.
<xsl:stylesheet>
<xsl:template match="para">
<xsl:apply-templates select="following-sibling::*[1]">
<xsl:with-param name="preceding" select="."/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="para[position() > 1]">
<xsl:param name="preceding"/>
<!-- do something -->
</xsl:template>
</xsl:stylesheet>
Sometimes you want a parameter to be available not just for the next template call or match, but later on during processing.
To do this, you need to set the @tunnel parameter on both the xsl:with-param where you define the parameter value as well as the xsl:param in the receiving template:
<xsl:template match="country">
<xsl:apply-templates select="* except desc"/>
<xsl:apply-templates select="desc">
<xsl:with-param name="reg" select="region" tunnel="yes"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="desc">
<h3>Description</h3>
<xsl:apply-templates mode="generated-text" select="../name"/>
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="name" mode="generated-text">
<xsl:param name="reg" tunnel="yes"/>
<p><xsl:value-of select="."/> is a country in the region of <xsl:value-of select="$reg"/></p>
</xsl:template>
@asNumerous XSL instructions accept the @as attribute, which takes the
allowed/expected type name as its value
<xsl:variable name="average" select="avg($nodes)" as="xs:double"/>
We'll see more examples of these as we go along!
It is best practice to specify types on functions, variables and parameters.
The following items are all 'deemed empty':
* Attributes do not count as child nodes!
xsl:on-emptyThis instruction contains instructions for a sequence. This sequence is only output if all of the previous sibling instructions produce empty results.
<xsl:apply-templates select="country"/>
<xsl:on-empty>
<p>No countries found.</p>
</xsl:on-empty>
You can only use one xsl:on-empty in any given sequence constructor.
xsl:on-non-emptyThis instruction contains instructions for a sequence. This sequence is only output if any sibling instruction produces non-empty results*
<xsl:apply-templates select="cost"/>
<xsl:on-non-empty>
<p><strong>total:</strong> <xsl:value-of select="sum(cost)"/></p>
</xsl:on-non-empty>
Except for other xsl:on-non-empty or xsl:on-empty instructions!
xsl:where-populatedThis instruction is a wrapper around other instructions that create a sequence. The resulting sequence is only produced if it is not empty
Example - HTML lists:
<xsl:where-populated>
<ul class="ticklist">
<xsl:apply-templates/>
</ul>
</xsl:where-populated>
This ul element is only produced in the output tree where li are generated by the use of xsl:apply-templates; the @class does not stop the node from being empty.
<div id="students">
<xsl:where-populated> <!-- no table without thead/tbody -->
<table>
<xsl:on-non-empty><!-- no thead without tbody -->
<thead><tr><th>Name</th><th>Age</th></tr></thead>
</xsl:on-non-empty>
<xsl:where-populated><!-- no tbody without tr -->
<tbody>
<!-- populates table rows -->
<xsl:apply-templates select="student"/>
</tbody>
</xsl:where-populated>
</table>
</xsl:where-populated>
<xsl:on-empty> <!-- output if no table. -->
<p>There are no students</p>
</xsl:on-empty>
</div>
xsl:elementxsl:element allows you to create new elements in the output dynamically. You
can use this to control the namespace of the output element as well as the input.
<xsl:template match="*">
<xsl:element name="{local-name(.)}" namespace="http://my.shiny.namespace.com/">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
Note that only the namespace is guaranteed - the prefix will depend on how your namespaces are declared in the output tree!
xsl:attributexsl:attribute is much like xsl:element except that it creates
attributes.
<xsl:template match="country">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="population|gdp">
<xsl:attribute name="{local-name(.)}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
The previous slides showed a little bit of new syntax:
<xsl:element name="{local-name()}"/>
The code in braces - {local-name()} is an attribute value template.
Because we can't use xsl:apply-value-of inside an attribute we use AVTs
instead.
As of XSLT 3, you can also use these braces to evaluate XPath in general text. This
can be turned on (or off) by specifying @expand-text on an ancestor instruction:
<xsl:text expand-text="yes">The table with id "{@id}" has {$footnote-count} footnotes.</xsl:text>
xsl:function creates new functions
<xsl:function as="xs:float" name="cfn:total">
<xsl:param as="xs:float" name="price"/>
<xsl:param as="xs:integer" name="qty"/>
<xsl:sequence select="$price * $qty"/>
</xsl:function>
Best practice is to use xsl:sequence in preference to xsl:value-of unless the returned item is a text node.