# ForEach Mediator

The ForEach mediator provides a general loop construct as a mediator. It allows a message to be processed iteratively while maintaining the original message context. The ForEach mediator split the message into a number of different messages derived from the parent message, by finding matching elements for the XPath expression that is specified. New messages will be created for all each of the matching elements and processed in sequence within the main flow using specified sequence. However, Call, CallOut or Send mediators are not allowed in the sequence. The original message will be modified by replacing the split elements with the elements that go through the loop construct.

Figure1: ForEach Mediator

ForEach Mediator can be configured with the following options.

- ForEach ID: Can be used to identify messages created by the foreach mediator. Useful when defining nested foreach mediators.
- Expression: Xpath expression that matches the elements which you want to split the message from. For XPath, namespaces can be specified by clicking the namespace link in the right hand side.
- Sequence: Mediates the message through a sequence. You can either pick a named sequence from the registry or define an anonymous sequence by adding mediators as children.

Foreach mediator will create two properties during mediation.

- <ForEachID>_FOREACH_ORIGINAL_MESSAGE : Contains the original envelope as when entered foreach mediator
- <ForEachID>_FOREACH_COUNTER : Contains the count of the messages processed. This will increment during each iteration.

Both these properties are defined in default (synapse) scope. Defining ForEach ID is optional. If not defined the properties will be defined without the prefix. However, in a nested foreach scenario it is best to define the ForEach ID to avoid properties getting overwritten.