Herong's Tutorial Notes On XML Technologies
Dr. Herong Yang, Version 3.04

XSL - Getting Values Out Of Source Elements

Part:   1  2  3  

(Continued from previous part...)

Openning dictionary_xsl.xml with Internet Explorer, I got:

d_dictionary
  
w__word
a___acronym=true
e___name
t____XML
e___definition
t____eXtensible Markup 
Language.
e___update
a____date=2002-12-23
w__word
a___symbol=true
e___name
t____<
e___definition
t____Mathematical symbol representing the "less than" logical 
operation, like: 1<2.
e___definition
t____Reserved symbol in XML representing the beginning of 
tags, like: 
t____<p>Hello world!</p>

Note that:

  • The leading character tells me where that piece of output came from.
  • The CDATA section in the last "definition" element was parsed as a separated text part. That's why I got two pieces of output out of this element.

The 'if' Element

if: An XSL element, serving as a conditional statement. If the specified condition is satisfied, the enclosed statements will be processed. Otherwise, they will be ignored.

<xsl:if test="condition">
 XSL statements
</xsl:if>

where "condition" is a logical expression.

The 'choose' Element

choose: An XSL element, serving as a conditional selection statement. This is like the "if-else" statement in many other computer languages.

<xsl:choose>
 <xsl:when test="condition1">
  XSL statements
 </xsl:when>
 <xsl:when test="condition2">
  XSL statements
 </xsl:when>
 ...
 <xsl:otherwise>
  XSL statements
 </xsl:otherwise>
</xsl:choose>

where "condition1" and "condition2" are logical expressions.

The 'variable' Element

variable: An XSL element, serving as a variable declaration statement. The variable name is the value of the "name" attribute. The variable value is the content of the statement element.

<xsl:variable name="variable_name">variable_value</xsl:variable>

Once a variable is define, its value can be referred by its name pre-fixed with a dollar sign "$". A variable can only be accessed in the same sub-tree where it is defined. For example:

<xsl:template match="document">
 <xsl:variable name="author"><xsl:value-of 
  select="property/@author"/></xsl:variable>
 <xsl:for-each select="chapter">
  Author: <xsl:value-of select="$author">
  ...
 </xsl:for-each>
</xsl:template>

In this code, I stored the value of attribute "author" in element "property" in variable "author". Then I used this variable in the "for-each" loop.

Conclusion:

  • "value-of" statement can be used to retrieve text information out of the source element.
  • "for-each" statement can be used to perform a loop over a group of sub elements or attributes.
  • "if" or "choose" statement can be used to create a conditional block.
  • "variable" statement can be used to define a variable to hold a value.

Part:   1  2  3  

Dr. Herong Yang, updated in 2006
Herong's Tutorial Notes On XML Technologies - XSL - Getting Values Out Of Source Elements