XML technologies / XSLT / Java and XSLT / XSLT – Advanced techniques / Formatting text and numbers

(Excerpt from “Java und XSLT” by Eric M. Burke)

XSLT and XPath define a small set of text and numeric functions: concatenation, substring extraction, string length and similar tasks. Though less powerful than Java, they handle many common operations.

Formatting numbers

The format-number( ) function converts numbers such as 123 to formatted values such as EUR 123,00. Its syntax is:

string format-number(zahlenwert, string, string?)

The first parameter is the number, the second a pattern and the optional third the name of an <xsl:decimal-format> element. We cover only the first two. Interestingly, behavior of format-number( ) is defined by JDK 1.1.x class java.text.DecimalFormat. Consult JDK 1.1.x documentation for the second argument’s full syntax.

Currency output commonly uses format-number( ). Pattern EUR #,##0.00 formats Euro values. This table shows sample inputs and outputs.

Table: Currency formatting with EUR #,##0.00

Number

Result

0

EUR 0,00

0,9

EUR 0,90

0,919

EUR 0,92

10

EUR 10,00

1000

EUR 1.000,00

12345,12345

EUR 12.345,12

Example XSLT usage is:

<xsl:value-of select="format-number(betrag,'EUR #,##0.00')"/>

Assume betrag is an XML element (the XSLT specification does not define what happens if the XML contains no valid number), for example <betrag>1000</betrag>. The characters # and 0 are digit placeholders behaving exactly as defined by java.text.DecimalFormat. Essentially, 0 stands for any digit, while # is omitted when the input is 0.

Percentages are another common format. End the pattern with %. Some examples follow:

<!-- gibt 0% aus -->
<xsl:value-of select="format-number(0,'0%')"/>

<!-- gibt 10% aus -->
<xsl:value-of select="format-number(0.1,'0%')"/>

<!-- gibt 100% aus -->
<xsl:value-of select="format-number(1,'0%')"/>

Again, the first argument to format-number( ) is the number, the second the pattern. Pattern digit 0 ensures at least one digit is displayed. Character % also multiplies by 100: 0.15 becomes 15% and 1 becomes 100%.

Test more patterns with this XML, together with zahlenFormatierung.xslt, showing every number/pattern combination.

 

Example: zahlenFormatierung.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="zahlenFormatierung.xslt"?>
<zahlenFormatierung>
   <formatBeispiele>
      <!-- fügen Sie mehr <format>-Elemente hinzu, um andere Kombinationen zu testen-->
      <format>EUR #,##0.00</format>
      <format>#.#</format>
      <format>0.#</format>
      <format>0.0</format>
      <format>0%</format>
      <format>0.0#</format>
   </formatBeispiele>
   <zahlenBeispiele>
      <!-- fügen Sie mehr <format>-Elemente hinzu, um andere Kombinationen zu testen-->
      <zahl>-10</zahl>
      <zahl>-1</zahl>
      <zahl>0</zahl>
      <zahl>0,000123</zahl>
      <zahl>0,1</zahl>
      <zahl>0,9</zahl>
      <zahl>0,91</zahl>
      <zahl>0,919</zahl>
      <zahl>1</zahl>
      <zahl>10</zahl>
      <zahl>100</zahl>
      <zahl>1000</zahl>
      <zahl>10000</zahl>
      <zahl>12345,12345</zahl>
      <zahl>55555,55555</zahl>
   </zahlenBeispiele>
</zahlenFormatierung>

The stylesheet, zahlenFormatierung.xslt, follows. Comments explain each step. To test new patterns, edit XML and rerun the transformation. The XML references its stylesheet with <?xml-stylesheet?>, so load it in an XSLT browser and refresh to see changes.

 

Example: zahlenFormatierung.xslt

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="html"/>
   <xsl:template match="/">
      <html>
         <body>
            <!-- eine Schleife für jedes der Beispielformate -->
            <xsl:for-each select="zahlenFormatierung/formatBeispiele/format">
               <h2>
                  <!-- das Format als Kopfzeile anzeigen -->
                  <xsl:value-of select="."/>
               </h2>
               <table border="1" cellpadding="2" cellspacing="0">
                  <tr>
                     <th>Zahl</th>
                     <th>Ergebnis</th>
                  </tr>
                  <!-- das Format als Parameter an das Template zur Anzeige jeder Zahl übergeben -->
                  <xsl:apply-templates select="/zahlenFormatierung/zahlenBeispiele/zahl">
                     <xsl:with-param name="fmt" select="."/>
                  </xsl:apply-templates>
               </table>
            </xsl:for-each>
         </body>
      </html>
   </xsl:template>
   <!-- Ausgeben der Zahl, gefolgt vom Ergebnis der format-number()-Funktion -->
   <xsl:template match="zahl">
      <xsl:param name="fmt"/>
      <tr>
         <td align="right">
            <xsl:value-of select="."/>
         </td>
         <td align="right">
            <!-- Der erste Parameter ist ein Punkt, der den Textinhalt des <zahl>-Elements repräsentiert -->
            <xsl:value-of select="format-number(.,$fmt)"/>
         </td>
      </tr>
   </xsl:template>
</xsl:stylesheet>

First iterate over <format> elements:

<xsl:for-each select="zahlenFormatierung/formatBeispiele/format">

Inside the loop, select all <zahl> elements, applying each format to every number:

<xsl:apply-templates select="/zahlenFormatierung/zahlenBeispiele/zahl">

Formatting text

XPath defines text functions for concatenation, substring extraction and length calculation. Unlike Java, XSLT and XPath string positions start at 1 rather than 0.

Suppose a stylesheet defines these variables:

<xsl:variable name="vorname" select="'Eric'"/>
<xsl:variable name="nachname" select="'Burke'"/>
<xsl:variable name="mittelname" select="'Matthew'"/>
<xsl:variable name="vollerName" select="concat($vorname, ' ', $mittelname, ' ', $nachname)"/>

The first three use quotes to mark string values. Without quotes, the XSLT processor would interpret XPath expressions and select matching input nodes. The fourth variable, vollerName, shows how concat( ) concatenates two or more strings supplied as a comma-separated argument list. Here Eric Matthew Burke is the value of vollerName.

The following table gives more string-function examples using the same variables. The first column lists return type, function name and parameters; the others show a call and its output.

Table: String-function examples

Function syntax

Example

Output

string concat(string,string,string*)

concat($vorname, ' ', $nachname)

Eric Burke

boolean starts-with(string,string)

starts-with($vorname, 'Er')

true

boolean contains(string,string)

contains($vollerName, 'Smith')

false

string substring-before(string,string)

substring-before($vollerName, ' ')

Eric

string substring-after(string,string)

substring-after($vollerName, ' ')

Matthew Burke

string substring(string,number,number?)

substring($mittelname,1,1)

M

number string-length(string?)

string-length($vollerName)

18

string normalize-space(string?)

normalize-space(' test ')

test

string translate(string,string,string)

translate('test','aeiou','AEIOU')

tEst

All string comparisons, such as starts-with() and contains( ), are case-sensitive, with no XSLT switch to disable this. Convert both strings to the same case first. Current XSLT does not directly support this conversion either, but translate( ) can do it. This converts lowercase to uppercase:

translate($text,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')

In functions substring-before( ) and substring-after( ), the second argument is a delimiter string, not necessarily one character. If absent from the input, the result is empty. Use them to parse formatted data such as dates:

<datum>25.06.2001</datum>

Extract day, month and year with:

<xsl:variable name="datumsStr" select="//datum"/>
<xsl:variable name="monatJahr" select="substring-after($datumsStr, '.')"/>
Tag: <xsl:value-of select="substring-before($datumsStr, '.')"/> <br/>
Monat: <xsl:value-of select="substring-before($monatJahr, '.')"/> <br/>
Jahr: <xsl:value-of select="substring-after($monatJahr, '.')"/>

The first line initializes variable datumsStr with the full date. Next, variable monatJahr contains everything after the first ., here datumsStr=25.06.2001 and monatJahr=06.2001. Java simplifies this: create a StringTokenizer instance and iterate over tokens, or use lastIndexOf( ) on java.lang.String to locate the second .. XSLT offers fewer options. The remaining lines split the variables into substrings, again delimited by a dot (.). The output follows:

Tag: 25
Monat: 06
Jahr: 2001

Another form of substring( ) takes two or more numbers giving the starting index and optional length of the substring. Without the second number, the substring continues to the end. Indices start at 1. The following examples show calls with their results: substring("abcde",2,3) bcd; substring("abcde",2): bcde.

   

 

 

 

back to top