FOR function
The FOR field function evaluates an expression and assigns a resulting value of TRUE, FALSE, or UNKNOWN.
Syntax
FOR enables you to write an expression that iterates over all instances of a repeating field. For each instance it processes a boolean expression and collates the results.
For example:
FOR ALL Body.Invoice.Purchases."Item"[] AS I (I.Quantity <= 50)
Note:
- With the quantified predicate , the first thing to note is the
[] on the end of the field reference after the FOR ALL. The square
brackets define iteration over all instances of the
Item
field.In some cases, this syntax appears unnecessary, because you can get that information from the context, but it is done for consistency with other pieces of syntax.
-
The ASclause associates the name
I
in the field reference with the current instance of the repeating field. This is similar to the concept of iterator classes used in some object oriented languages such as C++. The expression in parentheses is a predicate that is evaluated for each instance of theItem
field.
If you specify the ALL keyword, the function
iterates over all instances of the field Item inside
Body.Invoice.Purchases
and
evaluates the predicate I.Quantity <= 50
. If the
predicate evaluates to: - TRUE (if the field is empty, or for all instances of
Item
) return TRUE. - FALSE (for any instance of
Item
) return FALSE. - Anything else, return UNKNOWN.
The ANY and SOME keywords are equivalent.
If you use either, the function iterates over all instances of the
field Item inside
Body.Invoice.Purchases
and evaluates
the predicate I.Quantity <= 50
. If the predicate
evaluates to: - FALSE (if the field is empty, or for all instances of
Item
) return FALSE. - TRUE (for any instance of
Item
) return TRUE. - Anything else, return UNKNOWN.
To further illustrate this, the following examples are
based on the message described in Example message. In the following filter expression:
FOR ANY Body.Invoice.Purchases."Item"[] AS I (I.Title = 'The XML Companion')
the
sub-predicate evaluates to TRUE. However, this next expression returns
FALSE: FOR ANY Body.Invoice.Purchases."Item"[] AS I (I.Title = 'C Primer')
because
the C Primer is not included on this invoice. If in this instance
some of the items in the invoice do not include a book title field,
the sub-predicate returns UNKNOWN, and the quantified predicate returns
the value UNKNOWN.Take great care to deal with the possibility of null values
appearing. Write this filter with an explicit check on the existence
of the field, as follows:
FOR ANY Body.Invoice.Purchases."Item"[] AS I (I.Book IS NOT NULL AND
I.Book.Title = 'C Primer')
The IS NOT NULL predicate ensures
that, if an Item
field does not contain a Book
,
a FALSE value is returned from the sub-predicate.