Creating for Expressions

Creating for Expressions

XPath provides the for expression so that you can iterate over data. Here's how the for expression works in general:

 for  variable  in  sequence  return  expression  

Here, the variable is called the range variable , the value of the expression that follows the in keyword is called the input sequence , and the expression that follows the return keyword is called the return expression .

The result of the for expression is obtained by evaluating the return expression once for each item in the input sequence. The resulting sequence is returned (if multiple sequences are generated, they are concatenated ).

You can see an example in ch08_02.xsl , where we're using a for expression to create a sequence of all the planet names in our planetary data XML document:

 for $variable in //planet return $variable/name 

To display our results using an XPath 2.0 style sheet, we'll use the <xsl:value-of> element to insert the result sequence of names into the output. That means we have to use this element's separator attribute to indicate what text we want inserted between items in the sequenceif you don't use this attribute, you'll only get the first item in the sequence. You can see what the XSLT 2.0 style sheet looks like in ch08_02.xsl (Listing 8.2).

Listing 8.2 An XSLT Example Using the for Expression ( ch08_02.xsl )
 <xsl:stylesheet version="2.0"     xmlns:xsl=""     xmlns:xs="">     <xsl:template match="/">  <xsl:value-of select="for $variable in //planet return $variable/name"   separator=", "/>  </xsl:template> </xsl:stylesheet> 

And here's the result when we use Saxon to apply the ch08_02.xsl style sheet to our planetary data document:

 C:\Saxon>java net.sf.saxon.Transform ch02_01.xml ch08_02.xsl <?xml version="1.0" encoding="UTF-8"?> Mercury, Venus, Earth 

As you can see, we do indeed get all three planetary names this way. A for expression can also use multiple variables. For example, this expression uses two variables at once:

 for $x in (1, 2)     $y in (3, 4) return ($x * $y) 

The result of this for expression is the sequence (3, 4, 6, 8).

XPath. Navigating XML with XPath 1.0 and 2.0 Kick Start
XPath Kick Start: Navigating XML with XPath 1.0 and 2.0
ISBN: 0672324113
EAN: 2147483647
Year: 2002
Pages: 131

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: