XSLT
XSLT is a language that turns an XML document into text, CSV, HTML or other XML by following a stylesheet. .NET compiles stylesheets with XslCompiledTransform; this lesson makes a report, a CSV file and an HTML table from the same data.
What you will learn#
- what a stylesheet is and how
XslCompiledTransformruns it, - templates,
for-each,sort,sumand filters, - three outputs from one input: text, CSV and HTML,
- how this class looks from Ring.
The idea#
You have data in XML (the tutorial XML in depth) and you want a report. You can walk the tree in Ring, or you can write a stylesheet: a small XML document of templates ("when you see this part of the input, write this"). The advantage is that the stylesheet is data: change it, and the report changes, without touching the program.
<"t">class="k">xsl:template "t">match="/library">
<"t">class="k">xsl:for-each "t">select="book">
<"t">class="k">xsl:sort "t">select="@year" "t">data-type="number" "t">order="descending"/>
<"t">class="k">xsl:value-of "t">select="title"/> (<"t">class="k">xsl:value-of "t">select="@year"/>)
</"t">class="k">xsl:for-each>
</"t">class="k">xsl:template>select and match are XPath expressions (the tutorial XML in depth).
The program#
# XSLT - turn XML into text, CSV and HTML with a stylesheet (System.Xml.Xsl)
load "dotnet.ring"
using {
"System"
"System.IO"
"System.Xml.Xsl"
}
C_XML = '<library><book year="1937" genre="fantasy"><title>The Hobbit</title><price>9.5</price></book><book year="1965" genre="scifi"><title>Dune</title><price>12</price></book><book year="1984" genre="scifi"><title>Neuromancer</title><price>8.25</price></book></library>'
# A stylesheet is XML too: a template says what to write for a part of the input. xsl:output chooses the kind of result.
C_TEXT = '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="text"/>'
C_TEXT += '<xsl:template match="/library"><xsl:for-each select="book"><xsl:sort select="@year" data-type="number" order="descending"/>'
C_TEXT += '<xsl:value-of select="title"/> (<xsl:value-of select="@year"/>)<xsl:text> </xsl:text></xsl:for-each>'
C_TEXT += 'Total: <xsl:value-of select="sum(book/price)"/></xsl:template></xsl:stylesheet>'
C_CSV = '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="text"/>'
C_CSV += '<xsl:template match="/library">title,year,price<xsl:text> </xsl:text><xsl:for-each select="book[price < 10]">'
C_CSV += '<xsl:value-of select="title"/>,<xsl:value-of select="@year"/>,<xsl:value-of select="price"/><xsl:text> </xsl:text></xsl:for-each></xsl:template></xsl:stylesheet>'
C_HTML = '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="html" indent="yes"/>'
C_HTML += '<xsl:template match="/library"><table><xsl:for-each select="book"><tr class="{@genre}"><td><xsl:value-of select="title"/></td><td><xsl:value-of select="price"/></td></tr></xsl:for-each></table></xsl:template></xsl:stylesheet>'
func main
cFolder = new Path().Combine([new Path().GetTempPath(),"ringdotnet_xslt"])
new Directory().CreateDirectory(cFolder)
cInput = new Path().Combine([cFolder,"library.xml"])
new File().WriteAllText([ :path = cInput, :contents = C_XML ])
# 1. XSLT turns an input document into another document. XslCompiledTransform compiles the stylesheet once; Transform runs it.
? "1. a text report, newest book first, with the total price:"
? indent(transform(cFolder,cInput,C_TEXT,"report.txt"))
# 2. The same data as CSV, only the books cheaper than 10 (a filter inside the select)
? nl + "2. CSV of the cheap books:"
? indent(transform(cFolder,cInput,C_CSV,"cheap.csv"))
# 3. HTML: the result is a document that a browser can show. {@genre} puts the attribute into the class of the row.
cHtml = transform(cFolder,cInput,C_HTML,"table.html")
? nl + "3. an HTML table (" + len(cHtml) + " characters) with " + countOf(cHtml,"<tr") + " rows; the genres became classes: " + yesNo(substr(cHtml,'class="scifi"') > 0)
# 4. The HTML that the third stylesheet wrote
? nl + "4. the HTML:"
? indent(cHtml)
new Directory().Delete([ :path = cFolder, :recursive = True ])
# compile the stylesheet text, run it over the input file, return the text of the output file
func transform cFolder, cInput, cStylesheet, cOutputName
cSheet = new Path().Combine([cFolder,cOutputName + ".xsl"])
cOutput = new Path().Combine([cFolder,cOutputName])
new File().WriteAllText([ :path = cSheet, :contents = cStylesheet ])
oTransform = new XslCompiledTransform()
oTransform.@Load(cSheet)
oTransform.Transform([ :inputUri = cInput, :resultsFile = cOutput ])
return new File().ReadAllText(cOutput)
func indent cText
cText = substr(cText,char(13),"")
while right(cText,1) = char(10)
cText = left(cText,len(cText) - 1)
end
return " " + substr(cText,char(10),nl + " ")
func countOf cText, cPart
nCount = 0
nPos = 1
while true
nFound = substr(substr(cText,nPos,len(cText)),cPart)
if nFound = 0
exit
ok
nCount++
nPos += nFound + len(cPart) - 1
if nPos > len(cText)
exit
ok
end
return nCount
func yesNo lValue
if lValue
return "yes"
ok
return "no"1. a text report, newest book first, with the total price:
Neuromancer (1984)
Dune (1965)
The Hobbit (1937)
Total: 29.75
2. CSV of the cheap books:
title,year,price
The Hobbit,1937,9.5
Neuromancer,1984,8.25
3. an HTML table (236 characters) with 3 rows; the genres became classes: yes
4. the HTML:
<table>
<tr class="fantasy">
<td>The Hobbit</td>
<td>9.5</td>
</tr>
<tr class="scifi">
<td>Dune</td>
<td>12</td>
</tr>
<tr class="scifi">
<td>Neuromancer</td>
<td>8.25</td>
</tr>
</table>How it works#
The Ring side#
Everything happens in transform: it writes the stylesheet text to a file, then
oTransform = new XslCompiledTransform()
oTransform.@Load(cSheet) # compile the stylesheet (Load is a Ring keyword, so the method is @Load)
oTransform.Transform([ :inputUri = cInput, :resultsFile = cOutput ]) # input file -> output file@Load and Transform take file names in this form; the output file is read back with File.ReadAllText. Compiling is the slow part, so a program that transforms many documents compiles the stylesheet once and calls Transform many times.
Three stylesheets#
- Text.
xsl:output method="text"writes plain text.for-each select="book"repeats for every book;xsl:sortorders them by year, newest first (data-type="number", otherwise1965sorts after1937only by luck);sum(book/price)adds the prices.<xsl:text> </xsl:text>writes a new line. - CSV. The same structure, with a filter:
book[price < 10]keeps only the cheap books (<is<inside XML). - HTML.
method="html" indent="yes"writes a table. In<tr class="{@genre}">the braces put the value of the attribute into the output (an attribute value template), so each row gets its genre as a CSS class.
Writing XSLT strings in Ring code gets crowded. Keep stylesheets in their own .xsl files next to the program and pass the path to @Load; designers can then change the layout of a report without reading Ring.
When to use it#
- The result is a document with a fixed structure (reports, feeds, HTML pages from XML data).
- The people who change the layout are not the people who write the program.
- Not for logic: loops with counters, calls to your own functions and file access are easier in Ring.
What you learned#
XslCompiledTransform,@LoadandTransform,- templates,
for-each,sort,sum, filters, - text, CSV and HTML output,
- attribute value templates
{@name}.
Exercises#
- Write a stylesheet that outputs only the titles of the science fiction books.
- Add a
<xsl:if test="price > 10">that marks expensive books with*. - Make the HTML a complete page (
<html><body>…) with a heading and the total price. - Transform an XML file that you create with
XDocument(the tutorial XML in depth).