Sometimes we need to iterate over array elements in a BPEL process while performing an action such as a BPEL invoke
. This requires us to process repeating elements outside of an XSLT transform. In this recipe, we examine how to access repeating elements in an assign statement. We will iterate over the elements in a node-set; elements in the set are indexed starting with one.
We will need a source XML document to iterate over, and a target XML document to update with the results of our iteration.
0
.count
function and passing it to the node-set corresponding to the elements to be iterated over, as shown in the following code:count(bpws:getVariableData('outputVariable', 'payload', '/client:lowestQuotes/client:productLowestQuote'))
This can be created by dragging the expression editor onto the number of items variable, and in the Expression Builder by selecting Functions | Mathematical Functions | count and hitting Insert Into Expression. Then, select the elements to be iterated over and insert that XPath into the expression between the parentheses after the count function:
while
loop in the BPEL process by dragging the Component Palette | BPEL Constructs | While onto the BPEL process at the location where we want a loop. Open the while
activity and use the expression editor to create a suitable loop condition using the loop counter variable and the number of items variable; see the following example:bpws:getVariableData('CurrentIndex') < bpws:getVariableData('TotalProducts')
while
loop, we do it by indexing the repeating element with the current index variable, as shown in the following sample XPath, to select a productLowestQuote
record's product name:bpws:getVariableData('outputVariable','payload')
/client:productLowestQuote
[bpws:getVariableData('CurrentIndex')]
/client:productName
Note, that we can use this method to index either a source or a target variable.
When we select an element with an XPath expression, it actually returns a node-set of zero or more elements. If the result returns more than one node (the cardinality of the node-set is greater than one), then we can use the index variable and the while
loop to iterate across the elements in the node-set. It is important to remember when selecting from a node-set that the first element in the node-set is indexed by one.
If we need to add elements to a sequence in an assign
statement rather than just modify them, we need to use InsertAfter to place an XML Fragment at the correct point in the output document.
The ArrayProcessing
project in the code samples has a sample BPEL process called ArrayProcess.bpel
demonstrating this.