We often deal with repeating elements in XML. These repeating elements act as an array and need special processing constructs when used in XSLT. In this recipe, we show how to process an array using XSLT.
Create an XSLT stylesheet for an input schema and an output schema, both of which have repeating elements in them. An example schema fragment is shown as follows:
<element name="vendorQuote" maxOccurs="unbounded" type="tns:vendorQuoteType"/>
This element may repeat an unlimited number of times.
productLowestQuote
in this case):The for-each
construct loops over the top-level elements in the input node-set and creates an empty target element for each one. Any mappings under the for-each
construct are done in the context of the current node from the input node-set. For example, if the input document is as shown in the following code snippet, the node-set will contain three productQuote
nodes and a mapping from productName
will reference each of these nodes Revell B17G Flying Fortress 1:48 Scale
, Monogram B29 Superfortress 1:48
, and Airfix Avro Lancaster 1:72
in turn.
<productQuote> <productName>Revell B17G Flying Fortress 1:48</productName> ... </productQuote> <productQuote> <productName>Monogram B29 Superfortress 1:48</productName> </productQuote> <productQuote> <productName>Airfix Avro Lancaster 1:72</productName> ... </productQuote>
The ArrayProcessing
project in the code samples has a sample XSLT called ArrayTransformation.xsl
demonstrating this.
The for-each
construct can reference any arbitrary node-set and does not have to be tied to the input document directly; any XPath function that returns a node-set can be used as input.