XPath Expressions Module

From XForms Users Community Group

__NUMBEREDHEADINGS__



Document title:
XForms 2.0: XPath expression module
Editor
Nick Van den Bleeken, Inventive Designers
John M. Boyer, IBM
Abstract
This module defines how XPath is used for addressing instance data nodes in binding expressions, to express constraints, and to specify calculations in XForms. This module is based on XPath 2.0, but an XPath 1.0 backwards compatibility mode is provided to ensure that nearly all XPath 1.0 expressions continue to produce the same result with XPath 2.0.

This module also defines the XForms Function Library which contains additional functions that are useful for creating forms.

Status of this Document
This is a live wiki document. Although it often reflects the best understanding of the editors and members of the Working Group, it may be inaccurate and has not necessarily been reviewed. If you need a stable copy, use the most recent official version: http://www.w3.org/TR/xforms-xpath.

Copyright © 2010 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

About the XForms 2.0: XPath expression module

Introduction

This document is a module designed to add support for XPath as an expression language in XForms. XPath 2.0 is an expression language to address the nodes of [XML 1.0] or [XML 1.1] trees defined by W3C. It includes over 100 built-in functions, including operations on node-sets, strings, numbers, booleans, dates, and durations.

Besides defining how XPath can be used as an expression language in XForms this document also defines the XForms Function Library. The XForms Function Library contains additional functions that are useful for creating forms.

Reading the Specification

This specification has been written with various types of readers in mind—in particular XForms authors and XForms implementors. Implementors, however, should find all they need to add XPath 2.0 support to their XForms Processors. The specification begins with a general presentation of how XPath 2.0 expressions will be used in XForms before specifying the technical details of how to integrate XPath 2.0 in XForms. Finally it defines the XForms Function Library.

The specification has been written with various modes of presentation in mind. In case of a discrepancy, the online electronic version is considered the authoritative version of the document.

With regard to implementing behaviors defined for XForms content herein, this document uses the terms must, must not, required, shall, shall not, recommended, should, should not, may, and optional in accord with [RFC 2119]. Generally, the elements, attributes, functions and behaviors of XForms content defined in this specification are required to implement unless explicitly specified otherwise. The term author-optional, when applied to a content item such as an element, attribute, or function parameter, indicates to form authors that they may omit the content item and obtain the default behavior. The term author-optional is orthogonal to the conformance status (required, recommended, or optional) of the content item.

How the Specification is Organized

The specification is organized into the following chapters:

Chapters 1
An introduction to XPath as an expression language in XForms. The introduction and example usages of XPath expressions in XForms.
Chapter 2
Definition of the xpath-version attribute.
Chapter 3
Contains all the information on how XPath is integrated into XForms. This section is mostly targeted at XForms implementors.
Chapter 4
Defines the XForms Function library which defines additional functions that are useful for creating forms.

Documentation Conventions

Throughout this document, the following namespace prefixes and corresponding namespace identifiers are used:

xforms: The XForms namespace, e.g. http://www.w3.org/2002/xforms (see Namespace for XFormsXF)
xf: The XForms namespace, e.g. http://www.w3.org/2002/xforms (see Namespace for XFormsXF)
html: An XHTML namespace, e.g. http://www.w3.org/1999/xhtml (see [XHTML 1.0])
xs: The XML Schema namespace http://www.w3.org/2001/XMLSchema (see [XML Schema part 1])
xsi: The XML Schema for instances namespace http://www.w3.org/2001/XMLSchema-instance (see [XML Schema part 1])
ev: The XML Events namespace http://www.w3.org/2001/xml-events (see [XML Events])
fn: The XPath function namespace http://www.w3.org/2005/xpath-functions (see [Functions and Operators])
my: Any user defined namespace

This is only a convention; any namespace prefix may be used in practice.

The following typographical conventions are used to present technical material in this document.

Official terms are defined in the following manner: [Definition: You can find most terms in chapter 6 Glossary Of Terms]. Links to terms may be specially highlighted where necessary.

The XML representations of various elements within XForms are presented using the syntax for Abstract Modules in XHTML Modularization [XHTML Modularization].

Examples are set off typographically:

Example item
Example Item

References to external documents appear as follows: [Sample Reference] with links to the references section of this document.

Sample Reference
Reference - linked to from above.

The following typesetting convention is used for additional commentary:

Note:

A gentle explanation to readers.

Editorial note: Editorial Note Name
Editorial commentary, not intended for final publication.

Issue (sample-implementation-issue):

Issue-Name

A specific issue for which input from implementors is requested, for example as part of the Candidate Recommendation phase.

Resolution:

None recorded.

Examples

The following example binds an input control to an instance data node:

Input control bound to an instance data node
<input ref="order/shipTo/street" class="streetAddress">
  <label>Street</label>
  <hint>Please enter the number and street name</hint>
</input>

The following example outputs the total value of an order by calculating the sum of the price of all line totals in the order. The line total is calculated by multiplying the item price with number of items ordered:

XPath expression in output control
I charged you <output value="sum(for $i in order/order-item return $i/@price * $i/@qty)"/>

The xpath-version attribute

This module adds the xpath-version attribute to the XForms model element. The xpath-version attribute is used to switch on or off XPath 1.0 backwards compatibility mode. XPath 1.0 backwards compatibility mode ensures that nearly all XPath 1.0 expressions continue to deliver the same result with XPath 2.0.

xpath-version
Author-optional attribute used by the XForms processor to determine the XPath version that will be used to evaluate XPath expressions. The supported values are 1.0 and 2.0. For the default model the default value is :
  • 1.0 if the XForms conformance level is 1.0 or 1.1 (see The model elementXF for more information about the XForms conformance level)
  • 2.0 for all other XForms conformance levels.
For all non-default models the default value is the xpath-version of the default model. When an XForms processor doesn't supports the requested XPath version or any non-default model has a version setting that is incompatible with the XPath version selected by the XForms Processor, the XForms Processor dispatches the event xforms-xpath-version-error to the default model. If the event is not canceled, processing halts (this is the default action of the xforms-xpath-version-error event). If the event is canceled, XForms processing continues.

If XPath 1.0 compatibility mode is requested, an XForms processor may use either an XPath 1.0 implementation [XPath 1.0] or an XPath 2.0 implementation in XPath 1.0 compatibility mode [XPath 2.0]. If the XPath 1.0 engine can't evaluate an expression (as there are XPath 2.0 expressions which can't be executed with an XPath 1.0 engine, and some functions defined in [Functions and Operators] may be unavailable to an XPath 1.0 engine) an xforms-expression-error EventXF, xforms-binding-error EventXF, or xforms-action-error EventXF is dispatched.

Note:

XPath 1.0 only supports atomic values and node sets, and does not support sequences.

If an XPath 1.0 engine is used, the function signature components that accept or return:

  • A sequences atomic values are to be interpreted as accepting or returning a single atomic value
  • A sequence of items, nodes or elements are to be interpreted as accepting or returning a node-set

XPath Expressions in XForms

This module uses XPath to address instance data nodeXFs in binding expressions, to express constraints, and to specify calculations. XPath expressions in XForms are based on [XPath 2.0]. At the time of evaluation, an XPath expression must be syntactically correct. In addition, the namespaces the expression references must be in scope and the functions and variables it references must be defined.

If any of these conditions is not satisfied, an error is raised depending on the location of the expression: xforms-expression-error EventXF, xforms-binding-error EventXF, or xforms-action-error EventXF. The following extra context information is made available to any of these events:

Property Type Value
xpath-error xs:QName? [XPath 2.0] error identifier if available, otherwise the empty sequence.
xpath-error-items item()* XPath diagnostic values if available, otherwise the empty sequence.

Evaluation Context

This module extends the evaluation contextXF, with all the additional properties that are defined in the XPath expression contextXP. The expression context has two parts, the static contextXF, and the dynamic contextXF. The components that make up the expression context are defined in the XPath specification (see Section 2.1 Expression ContextXF). This section describes the way in which these components are initialized when an XPath expression is contained within a Form. The term containing element means in these sections the element within the form that is the parent of the attribute whose value contains the XPath expression in question.

The following two sections describe:

Initializing the Static Context

The static contextXP of an XPath expression appearing in a form is initialized as follows.

Initializing the Dynamic Context

For convenience, the dynamic context is described in two parts: the focus, which represents the place in the instance document that is currently being referenced, and a collection of additional context variables.

A number of functions specified in [Functions and Operators] are defined to be stableFO, meaning that if they are called twice during the same execution scopeFO, with the same arguments, then they return the same results (see "Section 1.7 TerminologyFO). XForms currently does not rigorously define what the same execution scope means, and leave it up to the implementor to choose when a new execution scope starts. This means, for example, that if the function current-dateTimeFO is called repeatedly in a form, the interval for which it produces the same result is implementation defined. The focus is not stable.

Note:

We are waiting for further implementation experience and user feedback to define what the same execution scope means for XForms.

Other components of the XPath Dynamic Context

The Core XForms specification explained how the focus for an XPath expression appearing in a Form is initialized. This section explains how the other components of the dynamic contextXP of an XPath expression are initialized.

  • The dynamic variablesXP are the current values of the in-scope variable binding elements.
  • The current date and time represents an implementation-dependent point in time during processing of an expression.
  • The implicit timezoneXP is implementation-defined.
  • The available documentsXP, and the available collectionsXP are implementation-defined.
  • The default collectionXP is implementation-defined. This allows options such as setting the default collection to be an empty sequence, or to be undefined.

Item type conversions

When the result of an expression needs to be converted to a built-in atomic type we will use the XPath constructor functions to do the conversion:

  • If the expected type is xs:string or xs:string?, then the argument is converted to a string as if by a call to the fn:string function
  • If the expected type is xs:boolean or xs:boolean?, then the argument is converted to a boolean as if by a call to the fn:boolean function

The XForms Function Library

XForms provides a library of functions available to all XPath expressions.

In addition to the standard XPath functions defined by [Functions and Operators], XForms defines a library of XPath functions called the XForms Function Library.

Functions are available in the following namespaces:

  • http://www.w3.org/2002/xforms-functions
    • This namespace exposes all XForms Function Library functions as well as all standard XPath functions.
    • The XPath static context's default function namespace must be set to this URI.
    • If there is a collision between the name of an XForms Function Library function and a standard XPath function, the standard XPath function takes precedence.
    • However, in backwards compatibility mode, precedence is reversed, and XForms Function Library functions take precedence over standard XPath functions.
  • http://www.w3.org/2002/xforms
    • This namespace exposes only XForms Function Library functions, and therefore doesn't expose standard XPath functions.
    • Note that this is the standard XForms namespace.

This split into two namespaces achieves the following:

  • All XForms Function Library functions as well as standard XPath functions are generally available without the need for a prefix.
  • For this reason, there is generally no need to map the URI http://www.w3.org/2002/xforms-functions to a prefix.
  • However form authors are free to be explicit when accessing functions in the XForms Function Library in order to strongly ensure the absence of name collision. In this case they can use a prefix such as xf or xforms, which is usually already mapped to http://www.w3.org/2002/xforms.

The function library provided by an XForms processor may also contain other extension functions as described in Extension FunctionsXF.

Error Handling

If an error occurs in an XPath function, then an xforms-expression-error EventXF, xforms-binding-error EventXF, or xforms-action-error EventXF is dispatched.

Boolean Functions

The boolean-from-string() Function

xf:boolean-from-string($value as xs:string) as xs:boolean

Function boolean-from-string returns true if the required parameter matches "true" or "1" using case-insensitive comparison. Otherwise false is returned. This function is useful when referencing a Schema xs:boolean datatype in an XPath expression.

The is-card-number() Function

xf:is-card-number($card-nr as xs:string?) as xs:boolean

If the string parameter conforms to the pattern restriction of the xforms:card-numberXF datatype, then this function applies the Luhn algorithm described in [Luhn Patent] and returns true if the number satisfies the formula. Otherwise, false is returned. If the parameter is omitted, it defaults to the string-value of the current context item.

Examples (see also xforms:card-numberXF):

xf:is-card-number(.)

returns true if and only if the string-value of the context item is a string of zero or more digits and satisfies the formula.

xf:is-card-number('4111111111111111')

returns true. Other examples of string constants that will return true are : 5431111111111111, 341111111111111 and 6011601160116611.

xf:is-card-number('123')

returns false.

The valid() Function

xf:valid() as xs:boolean

xf:valid($items as item()*) as xs:boolean

xf:valid($items as item()*, $relevant as xs:boolean) as xs:boolean

xf:valid($items as item()*, $relevant as xs:boolean, $recurse as xs:boolean) as xs:boolean

The valid() function returns the validity of XPath items, including instance data nodes.

The function acts as if first selecting items in this sequence:

  1. Selected items initially consist of each item referred to by the $items parameter, if present, or the expression's context item, if absent.
  2. If the $recurse attribute is omitted or set to true(), all nodes (including attribute nodes) for which a selected item is an ancestor node are also selected.
  3. If the $relevant attribute is omitted or set to true(), selected items which are non-relevant are deselected. The relevance information of an individual node is obtained by looking at the node's relevant property computed as per The xforms-recalculate EventXF. The relevance information of an XPath atomic value is always true().

If there are no resulting selected items, the function returns true().

Otherwise the function computes the logical AND of the validity of all the selected items. The validity information of an individual node is obtained by looking at the node validity computed as per The xforms-revalidate EventXF. The validity information of an XPath atomic value is always true().

If the function is used in a model binding expressionXF the XForms Processor should dispatch the event xforms-binding-error EventXF to the model. If the function is used in a computed expressionXF the XForms Processor should dispatch the event xforms-expression-error EventXF to the model.

Note:

The validity of a node might appear to be out of date by the time the valid() function is used if changes have been made to instance data between the time xforms-recalculate and/or xforms-revalidate processing occur and the time the function is called. This function must therefore be used with caution. Examples of safe use include:

  • In binding expressions, value expressions, and itemset expressions on form controls.
  • In action handlers responding to events dispatched to form controls, provided instance data has not changed since the time the default action for xforms-refresh has started.

Similarly, the reason for discouraging the use of the valid() function within binds is that it can easily return unexpected results. For example relevant="valid(../value)" will usually fail to produce the expected result as the relevant property is computed before revalidation happens.

<model>
  <instance>
    <data xmlns="">
      <node1/>
      <node2/>
    </data>
  </instance>
  <bind ref="*" type="xs:integer"/>
</model>
<repeat ref="*[not(valid())]">
  <output value=".">
    <label>Invalid value:</label>
  </output>
</repeat>

The repeat above generates an output to show the value of each data node that is not valid according to XForms model validation processing.

The relevant() Function

xf:relevant() as xs:boolean

xf:relevant($items as item()*) as xs:boolean

The relevant() function returns the relevance of XPath items, including instance data nodes.

Selected items consist of each item referred to by the $items parameter, if present, or the expression's context item, if absent.

If there are no resulting selected items, the function returns true().

Otherwise the function computes the logical AND of the relevance of all the selected items.

The relevance information of an individual node is obtained by looking at the node's relevant property computed as per The xforms-recalculate EventXF, including inheritance. The relevance information of an XPath atomic value is always true().

If the function is used in a model binding expressionXF the XForms Processor should dispatch the event xforms-binding-error EventXF to the model. If the function is used in a computed expressionXF the XForms Processor should dispatch the event xforms-expression-error EventXF to the model.

Note:

Similarly to the valid() function, the relevance of a node might appear to be out of date by the time the relevant() function is used if changes have been made to instance data between the time xforms-recalculate and/or xforms-revalidate processing occur and the time the function is called. This function must therefore be used with caution.

The readonly() Function

xf:readonly() as xs:boolean

xf:readonly($items as item()*) as xs:boolean

The readonly() function returns the readonly property of XPath items, including instance data nodes.

Selected items consist of each item referred to by the $items parameter, if present, or the expression's context item, if absent.

If there are no resulting selected items, the function returns false().

Otherwise the function computes the logical OR of the readonly property of all the selected items.

The readonly property information of an individual node is obtained by looking at the node's readonly property computed as per The xforms-recalculate EventXF, including inheritance. The readonly information of an XPath atomic value is always true().

If the function is used in a model binding expressionXF the XForms Processor should dispatch the event xforms-binding-error EventXF to the model. If the function is used in a computed expressionXF the XForms Processor should dispatch the event xforms-expression-error EventXF to the model.

Note:

Similarly to the valid() function, the readonly property of a node might appear to be out of date by the time the readonly() function is used if changes have been made to instance data between the time xforms-recalculate and/or xforms-revalidate processing occur and the time the function is called. This function must therefore be used with caution.

The required() Function

xf:required() as xs:boolean

xf:required($items as item()*) as xs:boolean

The required() function returns the required property of XPath items, including instance data nodes.

Selected items consist of each item referred to by the $items parameter, if present, or the expression's context item, if absent.

If there are no resulting selected items, the function returns false().

Otherwise the function computes the logical OR of the required property of all the selected items.

The required property information of an individual node is obtained by looking at the node's required property computed as per The xforms-recalculate EventXF. The required information of an XPath atomic value is always false().

If the function is used in a model binding expressionXF the XForms Processor should dispatch the event xforms-binding-error EventXF to the model. If the function is used in a computed expressionXF the XForms Processor should dispatch the event xforms-expression-error EventXF to the model.

Note:

Similarly to the valid() function, the required property of a node might appear to be out of date by the time the required() function is used if changes have been made to instance data between the time xforms-recalculate and/or xforms-revalidate processing occur and the time the function is called. This function must therefore be used with caution.

Number Functions

The avg() Function

The following function has two definitions:

  1. In XPath 2.0 mode, the standard XPath 2.0 avg function is used.
  2. In XPath 1.0 backwards compatibility mode, the following definition of the avg is made available and the standard XPath 2.0 avg function is not available.

xf:avg($arg as node()*) as xs:double

Function avg returns the arithmetic average of the result of converting the string-values of each node in the argument node-set to a number. The sum is computed with sum(), and divided with div by the value computed with count(). If the parameter is an empty node-set, or if any of the nodes evaluate to NaN, the return value is NaN.

The min() Function

The following function has two definitions:

  1. In XPath 2.0 mode, the standard XPath 2.0 min function is used.
  2. In XPath 1.0 backwards compatibility mode, the following definition of the min is made available and the standard XPath 2.0 min function is not available.

xf:min($arg as node()*) as xs:double

Function min returns the minimum value of the result of converting the string-values of each node in argument node-set to a number. "Minimum" is determined with the < operator. If the parameter is an empty sequence, or if any of the nodes evaluate to NaN, the return value is NaN.

The max() Function

The following function has two definitions:

  1. In XPath 2.0 mode, the standard XPath 2.0 max function is used.
  2. In XPath 1.0 backwards compatibility mode, the following definition of the max is made available and the standard XPath 2.0 max function is not available.

xf:max($arg as node()*) as xs:double

Function max returns the maximum value of the result of converting the string-values of each node in argument node-set to a number. "Maximum" is determined with the < operator. If the parameter is an empty sequence, or if any of the nodes evaluate to NaN, the return value is NaN.

The count-non-empty() Function

xf:count-non-empty($arg as node()*) as xs:integer

Function count-non-empty returns the number of non-empty nodes in the first argument. A node is considered non-empty if it is convertible into a string with a greater-than zero length.

The index() Function

xf:index($repeat-id as xs:string) as numeric

Function index takes a string argument that is the IDREF of a repeat and returns the current 1-based position of the repeat index for the identified repeat as an integer value —see The repeat ElementXF for details on repeat and its associated repeat index. If the specified argument does not identify a repeat, the function returns the double value NaN.

Note:

The IDREF obtained from the function parameter may not uniquely identify the desired repeat if the repeat element bearing the matching ID resides in a repeating construct such as element repeat. The general method described in Resolving ID References in XFormsXF is used to determine the desired run-time repeat object.

The function index introduces additional dependencies for the computational dependency data structure, see Additional dependencies for the computational dependency data structure for details.

index
<trigger>
  <label>Add to Shopping Cart</label>
  <insert
    ev:event="DOMActivate"
    position="after"
    ref="items/item"
    at="xf:index('cartUI')"/>
</trigger>

When activated, this trigger inserts a new item element as the successor of the item element indicated by the index() function.

The power() Function

xf:power($base as xs:double, $exponent as xs:double) as xs:double

Returns the result of raising the first argument to the power of the second argument. The value of power(0,0) is 1. Both arguments may be fractional and negative, however, power(0, y) returns NaN for negative y, and power(x, y) returns NaN for negative x and non integer y.

Examples:

xf:power(2, 3)

returns 8

xf:power(-1, 0.5)

returns NaN.

The random() Function

xf:random($seed as xs:boolean?) as xs:double

This function generates and returns a uniformly distributed random or pseudorandom number in the range from 0.0 up to but excluding 1.0. This function accepts an author-optional boolean parameter that is false by default. If true, the random number generator for this function is first seeded with a source of randomness before generating the return value. A typical implementation may seed the random number generator with the current system time in milliseconds when random(true) is invoked, and it may apply a linear congruential formula to generate return values on successive invocations of the function.

Example:

xf:random()

could return 0.14159265358979

The compare() Function

xf:compare($arg1 as xs:string, $arg2 as xs:string) as xs:integer

This function returns -1, 0, or 1, depending on whether the value of the first argument is respectively less than, equal to, or greater than the value of second argument based on lexicographic comparison using Unicode code point values [Unicode Collation Algorithm].

Example:

xf:compare('apple', 'orange')

returns -1

String Functions

The case() Function

xf:case($switch-id as xs:string) as xs:string?

Function case takes a string argument that is the IDREF of a switch and returns the ID of the selected case for the identified switch—see The switch ElementXF for details on switch.

The empty sequence is returned, if the specified argument does not identify a switch.

Note:

The IDREF obtained from the function parameter may not uniquely identify the desired switch if the switch element bearing the matching ID resides in a repeating construct such as element repeat. The general method described in Resolving ID References in XFormsXF is used to determine the desired run-time repeat object.

The function case introduces additional dependencies for the computational dependency data structure, see Additional dependencies for the computational dependency data structure for details.

The property() Function

xf:property($property-name as xs:string) as xs:string?

This function accepts a string identifying a property name. If the property name is not recognized, the empty sequence is returned. The property definitions for this function are as follows:

Property Return Value
version 1.1 or 2.0. This indicates which version of XForms the processor is currently running (possibly as selected by the version attribute on the model element).
conformance-level full, model, basic, or a string beginning with full, model, or basic. The value basic can only be returned if version returns 1.1.

Any other NCName

Reserved. If the implementation does not support the property, then the empty sequence is returned.

QNameButNotNCName

An implementation-specific property value, such as a locale or timezone for the user agent. If the implementation does not support the property, then the empty sequence is returned.


Examples:

xf:property('version')

returns 2.0

xf:property('conformance-level')

may return full

xf:property('personal')

returns the empty sequence.


The digest() Function

xf:digest($data as xs:string, $algo as xs:string, $encoding as xs:string?) as xs:string

This function accepts a string of data, a string indicating a cryptographic hashing algorithm, and an author-optional string indicating an encoding method. The data string is serialized as UTF-8, the hash value is then computed using the indicated hash algorithm, and the hash value is then encoded by the indicated method, and the result is returned by the function. The following table presents the keywords for the second string parameter and the corresponding hash algorithms:

Keywords Hash Algorithm Status
MD5

The MD5 hash algorithm defined in [MD5]

Required

SHA-1

The SHA-1 hash algorithm defined in [SHA2]

Required

SHA-256

The SHA-256 hash algorithm defined in [SHA2]

Required

SHA-384

The SHA-384 hash algorithm defined in [SHA2]

Optional

SHA-512

The SHA-512 hash algorithm defined in [SHA2]

Optional

Any other NCName

Reserved. Their use results in an exception (see 4 The XForms Function Library for the exception type)

Required

QNameButNotNCName

An implementation-specific hash algorithm is used. If the implementation does not support the indicated hash algorithm, then an exception occurs (see 4 The XForms Function Library for the exception type).

Required

This recommendation defines the values hex and base64 for the third string parameter that indicates the encoding method. If the parameter is missing, then the default is base64. The hex and base64 encoding methods of this function correspond to the encodings defined in [XML Schema part 2] for the datatypes hexBinary and base64Binary, respectively. For the hexadecimal encoding, the digits 'a' through 'f' are encoded with lower case letters. Any other string value given for the encoding method results in an exception (see 4 The XForms Function Library for the exception type).

xf:digest('abc', 'SHA-1', 'hex')

returns a9993e364706816aba3e25717850c26c9cd0d89d.

xf:digest('abc', 'MD5', 'hex')

returns 900150983cd24fb0d6963f7d28e17f72.

xf:digest('abc', 'SHA-256', 'hex')

returns ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

The hmac() Function

xf:hmac($secret as xs:string, $data as xs:string, $algo as xs:string, $encoding as xs:string?) as xs:string

This function accepts a string for a key or shared secret, a string of data, a string indicating a cryptographic hashing algorithm, and an author-optional string indicating an encoding method. The key and data strings are serialized as UTF-8, and they are subjected to the HMAC algorithm defined in [HMAC] and parameterized by the the hash algorithm indicated by the third parameter. The result is encoded with the method indicated by the fourth parameter, and the result is returned by the function.

The following table presents the keywords for the third string parameter and the corresponding hash algorithms:

Keywords Hash Algorithm Status
MD5

The MD5 hash algorithm defined in [MD5]

Required

SHA-1

The SHA-1 hash algorithm defined in [SHA2]

Required

SHA-256

The SHA-256 hash algorithm defined in [SHA2]

Required

SHA-384

The SHA-384 hash algorithm defined in [SHA2]

Optional

SHA-512

The SHA-512 hash algorithm defined in [SHA2]

Optional

Any other NCName

Reserved. Their use results in an exception (see 4 The XForms Function Library for the exception type)

Required

QNameButNotNCName

An implementation-specific hash algorithm is used. If the implementation does not support the indicated hash algorithm, then an exception occurs (see 4 The XForms Function Library for the exception type).

Required

This recommendation defines the values hex and base64 for the fourth string parameter that indicates the encoding method. If the parameter is missing, then the default is base64. The hex and base64 encoding methods of this function correspond to the encodings defined in [XML Schema part 2] for the datatypes hexBinary and base64Binary, respectively. For the hexadecimal encoding, the digits 'a' through 'f' are encoded with lower case letters. Any other string value given for the encoding method results in an exception (see 4 The XForms Function Library for the exception type).

xf:hmac('Jefe', 'what do ya want for nothing?', 'SHA-1', 'hex')

returns effcdf6ae5eb2fa2d27416d5f184df9c259a7c79

xf:hmac('Jefe', 'what do ya want for nothing?', 'MD5', 'hex')

returns 750c783e6ab0b503eaa86e310a5db738

xf:hmac('Jefe', 'what do ya want for nothing?', 'SHA-256', 'hex')

returns 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843

The serialize() Function

xf:serialize($arg as item()*) as xs:string

xf:serialize($arg as item()*, $params as element(output:serialization-parameters)?) as xs:string

This function serializes the supplied input sequence $arg as described in [XSLT and XQuery Serialization 3.0], returning the serialized representation of the sequence as a string. The function must behave as the XPath 3.0 functions of the same name as specified in [XPath and XQuery Functions and Operators 3.0].

As allowed by [XSLT and XQuery Serialization 3.0] XForms specifies two additional output methods:

  • xforms:json. When this method is specified, JSON serialization is performed following section External JSON valuesXF.
  • xforms:csv. When this method is specified, CSV serialization is performed following section External CSV valuesXF.

If any serialization error occurs, including the detection of an invalid value for a serialization parameter, this results in the xf:serialize() call failing with a dynamic error.

XForms also specifies the following additional serialization parameter:

Serialization parameter name Permitted values for parameter and meaning
xforms:relevant One of the enumerated values yes or no. When yes, non-relevant nodes in the input sequence specified by $arg are pruned. The default value is yes by consistency with xforms:submission.

Example:

<model>
   <xf:instance xmlns="">
      <data>
         <node>abc</node>
         <text>&lt;node&gt;abc&lt;/node&gt;</text>
      </data>
   </xf:instance>
   <bind ref="text" calculate="xf:serialize(../node, instance('serialization'))"/>
</model>

The function returns a string containing the serialization of element node following the serialization parameters held in the serialization instance. The result is placed into the content of the element text by the calculate attribute.


Date and Time Functions

Note:

The following XML Schema datatypes do not have specific functions for manipulation within XForms expressions: xs:gYearMonth, xs:gYear, xs:gMonthDay, xs:gDay, xs:gMonth. Extension functions (Extension FunctionsXF) may be used to perform needed operations on these datatypes.

The local-date() Function

xf:local-date() as xs:date

This function returns a lexical xs:date obtained as if by the following rules: the result of now() is converted to a local date based on the user agent time zone information. If no time zone information is available, then the date portion of the result of now() is returned.

Example:

xf:local-date()

could return 2006-10-13-07:00

xf:substring(local-date(), 1, 10)

could return 2006-10-13

xf:days-to-date(days-from-date(local-date()) + 31)

returns a date that is 31 days from today. For example, if local-date() returns 2006-10-13-07:00, then the result is 2006-11-13.

The local-dateTime() Function

xf:local-dateTime() as xs:dateTime

This function returns a lexical xs:dateTime obtained as if by the following rules: the result of now() is converted to a local dateTime based on the user agent time zone information. If no time zone information is available, then the result of now() is returned.

Example:

xf:local-dateTime()

could return 2006-10-13T16:04:17-07:00

xf:adjust-dateTime-to-timezone(seconds-to-dateTime(seconds-from-dateTime(local-dateTime()) + 7200))

Adds two hours (7200 seconds) to the local date and time, returning the result in the local time zone. For example, if local-dateTime() returns 2007-10-02T14:26:43-07:00, then the above expression returns 2007-10-02T16:26:43-07:00

The now() Function

xf:now() as xs:string

The now function returns the current UTC date and time as a string value in the canonical XML Schema xs:dateTime format. If time zone information is available, it is used to convert the date and time to UTC. If no time zone information is available, then the date and time are assumed to be in UTC.

Note:

Attaching a calculation of "now()" to an instance data node would not result in a stream of continuous recalculations of the XForms Model.

Examples:

xf:now()

returns 2006-10-14T01:04:17Z if local-dateTime() returns 2006-10-13T18:04:17-07:00

xf:seconds-to-dateTime(seconds-from-dateTime(now()) + 7200)

Computes two hours from now, returning the result in UTC time. For example, if now() returns 2007-10-02T21:26:43Z, then the above expression returns 2007-10-02T23:26:43Z

The days-from-date() Function

xf:days-from-date($arg as xs:string) as numeric

This function returns a whole number of days, according to the following rules:

If the string parameter represents a legal lexical xs:date or xs:dateTime, the return value is an integer value equal to the number of days difference between the specified date or dateTime (normalized to UTC) and 1970-01-01. Hour, minute, and second components are ignored after normalization. Any other input parameter causes a return of the double value NaN.

Note:

If an <coddiv class="exampleOuter">

e>xs:date is given as the parameter, the timezone is ignored if provided because there is no way to normalize to the date in the UTC timezone without both the time and timezone.

Examples:

xf:days-from-date("2002-01-01")

returns 11688

xf:days-from-date("2002-01-01-07:00")

returns 11688

xf:days-from-date("1969-12-31")

returns -1

The days-to-date() Function

xf:days-to-date($arg as xs:double) as xs:string

This function returns a string containing a lexical xs:date that corresponds to the number of days passed as the parameter according to the following rules:

The parameter is rounded to the nearest whole number, and the result is interpreted as the difference between the desired date and 1970-01-01. An input parameter value of NaN results in output of the empty string.

Examples:

xf:days-to-date(11688)

returns 2002-01-01

xf:days-to-date(-1)

returns 1969-12-31

The seconds-from-epoch() Function

xf:seconds-from-epoch($arg as xs:string) as xs:double

For XPath 1.0 backwards compatibility, see also the seconds-from-dateTime() function.

This function returns a possibly fractional number of seconds, according to the following rules:

If the string parameter represents a legal lexical xs:dateTime, the return value is equal to the number of seconds difference between the specified dateTime (normalized to UTC) and 1970-01-01T00:00:00Z. If no time zone is specified, UTC is used. Any other input string parameter causes a return value of NaN. This function does not support leap seconds.

Example:

xf:seconds-from-epoch('1970-01-01T00:00:00Z')

returns 0

xf:seconds-from-epoch('1970-01-01T00:00:00-08:00')

returns 28800

The seconds-from-dateTime() Function

xf:seconds-from-dateTime($arg as xs:string) as xs:double

Note:

This function is present for backwards compatibility only. Form authors should prefer the seconds-from-epoch() function, which offers the exact same semantic but under a name which doesn't clash with the XPath 2.0 function of the same name.

In XPath 2.0 mode:

  1. This function is available in the http://www.w3.org/2002/xforms namespace only.
  2. The seconds-from-dateTime function in the http://www.w3.org/2002/xforms-functions namespace refers to the standard XPath 2.0 function, which has a different signature and semantic.

In XPath 1.0 backwards compatibility mode, this function is available under the following namespaces:

  1. http://www.w3.org/2002/xforms-functions, where this function takes precedence over the standard XPath 2 function with the same name.
  2. http://www.w3.org/2002/xforms

The function behaves like the seconds-from-epoch() function.

Example:

xf:seconds-from-dateTime('1970-01-01T00:00:00Z')

returns 0

xf:seconds-from-dateTime('1970-01-01T00:00:00-08:00')

returns 28800

The seconds-to-dateTime() Function

xf:seconds-to-dateTime($arg as xs:double) as xs:string

This function returns a string containing a lexical xs:dateTime that corresponds to the number of seconds passed as the parameter according to the following rules:

The parameter is rounded to the nearest whole number, and the result is interpreted as the difference between the desired UTC dateTime and 1970-01-01T00:00:00Z. An input parameter value of NaN results in output of the empty string. This function does not support leap seconds.

Examples:

xf:seconds-to-dateTime(0)

returns 1970-01-01T00:00:00Z

xf:seconds-from-dateTime(28800)

returns 1970-01-01T08:00:00Z

xf:seconds-to-dateTime(seconds-from-dateTime(now()) + 7200)

Computes two hours from now, returning the result in UTC time. For example, if now() returns 2007-10-02T21:26:43Z, then the above expression returns 2007-10-02T23:26:43Z

xf:adjust-dateTime-to-timezone(seconds-to-dateTime(seconds-from-dateTime(now()) + 7200))

Computes two hours from now, returning the result in the local time zone. For example, if now() returns 2007-10-02T21:26:43Z and the local date and time is 2007-10-02T14:26:43-07:00, then the above expression returns 2007-10-02T16:26:43-07:00

The adjust-dateTime-to-timezone() Function

xf:adjust-dateTime-to-timezone($arg as xs:string) as xs:string

Note:

This function is present for backwards compatibility only. Form authors should prefer the XPath 2 function of the same name, which offers similar functionality.

In XPath 2.0 mode:

  1. This function is available in the http://www.w3.org/2002/xforms namespace only.
  2. The adjust-dateTime-to-timezone function in the http://www.w3.org/2002/xforms-functions namespace refers to the standard XPath 2.0 function, which has a different signature and semantic.

In XPath 1.0 backwards compatibility mode, this function is available under the following namespaces:

  1. http://www.w3.org/2002/xforms-functions, where this function takes precedence over the standard XPath 2 function with the same name.
  2. http://www.w3.org/2002/xforms

This function adjusts a legal lexical xs:dateTime received as the parameter to the local time zone for the user of the implementation, and returns the result. The application of daylight savings time is dependent on whether daylight savings time is in effect for the local time zone at the given date and time. "Local" or untimezoned times are presumed to be the time in the local time zone. If the implementation does not have access to time zone information, UTC is used. The result is empty string if the string argument is the empty sequence or not a legal lexical xs:dateTime.

Examples:

xf:adjust-dateTime-to-timezone('2007-10-07T02:22:00')

returns 2007-10-07T02:22:00-07:00 in the Pacific time zone since daylight savings time applies to the date 2007-10-02 in the Pacific time zone.

xf:adjust-dateTime-to-timezone('2007-10-02T21:26:43Z')

returns 2007-10-02T14:26:43-07:00 in the Pacific time zone since daylight savings time applies to the date 2007-10-02 in the Pacific time zone.

xf:adjust-dateTime-to-timezone(seconds-to-dateTime(seconds-from-dateTime(now()) + 7200))

Computes two hours from now, returning the result in the local time zone. For example, if now() returns 2007-10-02T21:26:43Z and the local date and time is 2007-10-02T14:26:43-07:00 in the Pacific time zone, then the above expression returns 2007-10-02T16:26:43-07:00

xf:adjust-dateTime-to-timezone(
  seconds-to-dateTime(seconds-from-dateTime('2007-10-02T14:26:43-07:00') + 61 * 86400)
)

Returns 2007-12-02T13:26:43-08:00, which is the date and time two months (61 days) from the date 2007-10-02T14:26:43-07:00 in the Pacific timezone, adjusting the result for the fact that daylight savings time no longer applies to the resultant date in the Pacific timezone. Note that the hour component is 13, not 14 and the timezone offset is -08:00, not -07:00.

The seconds() Function

xf:seconds($arg as xs:string) as numeric

This function returns a possibly fractional number of seconds, according to the following rules:

If the string parameter represents a legal lexical xs:duration, the return value is a decimal value equal to the number specified in the seconds component plus 60 * the number specified in the minutes component, plus 60 * 60 * the number specified in the hours component, plus 60 * 60 * 24 * the number specified in the days component. The sign of the result will match the sign of the duration. Year and month components, if present, are ignored. Any other input parameter causes a return of the double value NaN.

Note:

Even though this function is defined based on a lexical xs:duration, it is intended for use only with derived-from-xs:duration datatypes, specifically xforms:dayTimeDuration.

Examples:

xf:seconds("P3DT10H30M1.5S")

returns 297001.5 (3 days, 10 hours, 30 minutes, and 1.5 seconds)

xf:seconds("P1Y2M")

returns 0 because the year and month parts of the duration are ignored and the remaining portions are unspecified and default to 0

xf:seconds("3")

returns NaN because the parameter is not a lexically valid duration

The months() Function

xf:months($arg as xs:string) as numeric

This function returns a whole number of months, according to the following rules:

If the string parameter represents a legal lexical xs:duration, the return value is an integer value equal to the number specified in the months component plus 12 * the number specified in the years component. The sign of the result will match the sign of the duration. Day, hour, minute, and second components, if present, are ignored. Any other input parameter causes a return of the double value NaN.

Note:

Even though this function is defined based on a lexical xs:duration, it is intended for use only with derived-from-xs:duration datatypes, specifically xforms:yearMonthDuration.

Examples:

xf:months("P1Y2M")

returns 14 (1 year and 2 months)

xf:months("-P19M")

returns -19 because the duration is negative and expresses 0 years and 19 months

Node-set Functions

The instance() Function

xf:instance($id as xs:string?) as element()?

An XForms Model can contain more than one instance. This function allows access to instance data, within the same XForms Model, but outside the instance data containing the context node if any.

If the argument is omitted or is equal to the empty string, then the root element node (also called the document element node) is returned for the default instance of the current model. The current model, is the model that contains the node of the nearest inscope evaluation context that is a node (starting from the evaluation context of the the node containing the XPath expression that invokes this function).

Otherwise, the argument is converted to a string as if by a call to the string function. This string is treated as an IDREF, which is matched against instance elements in the containing document. If a match is located, and the matching instance data is associated with the same XForms Model as the current model, this function returns the root element node (also called the document element node) of the referenced instance data. In all other cases, an empty sequence is returned, including if a match is located but the given instance data does not have a root element node (which can be the case when creation of instance data from an external resource or inline content has failed).

Example:

For instance data corresponding to this XML:

<xforms:instance xmlns="" id="orderform">
  <orderForm>
    <shipTo>
      <firstName>John</firstName>
    </shipTo>
  </orderForm>
</xforms:instance>

The following expression selects the firstName node. Note that the instance function returns an element node, effectively replacing the leftmost location step from the path:

ref="xf:instance('orderform')/shipTo/firstName"

The current() Function

xf:current() as item()

Returns the context itemXP used to initialize the evaluation of the containing XPath expression.

Examples:

For the following instance data:

<xforms:instance xmlns="">
  <converter>
    <amount>100</amount>
    <currency>jpy</currency>
    <convertedAmount></convertedAmount>
  </converter>
</xforms:instance>
<xforms:instance xmlns="" id="convTable">
  <convTable date="20040212" currency="cdn">
    <rate currency="eur">0.59376</rate>
    <rate currency="mxn">8.37597</rate>
    <rate currency="jpy">80.23451</rate>
    <rate currency="usd">0.76138</rate>
  </convTable>
</xforms:instance>

and the following value calculation bind:

<bind
  ref="convertedAmount"
  calculate="
    ../amount *
    xf:instance('convTable')/rate[@currency=xf:current()/../currency]"/>

the content value of /converter/convertedAmount is the product of /converter/amount and the conversion table rate given by the rate element whose currency attribute value matches the content of /converter/currency.

For the following instance data:

<xforms:instance xmlns="" id="i1">
  <months>
    <mon>01</mon>
    <mon>02</mon>
    <mon>03</mon>
  </months>
</xforms:instance>
<xforms:instance xmlns="" id="i2">
  <months>
    <month code="01">Jan</month>
    <month code="02">Feb</month>
    <month code="03">Mar</month>
  </months>
</xforms:instance>

and the following repeat structure:

<repeat ref="mon">
   <output value="xf:instance('i2')/month[@code = xf:current()]/>
</repeat>


the output should contain Jan Feb Mar.

The id() Function

xf:id($arg as xs:string*, $node as node()*?) as element()*

xf:id($arg as node()*, $node as node()*?) as element()*

The first parameter provides one or more IDREFs. This may be in the form of a string containing a space-separated list of IDREFs or a sequence of nodes, each node of which contains an IDREF. The second parameter provides nodes in one or more instance data documents to be searched. If the second parameter is not given or is empty, then the instance data document to be searched is the one containing the context node of the function call (if the context item isn't a node and second parameter isn't provided or is the empty sequence an error is raised). For each node in the second parameter (or its default), the set of element nodes are collected with IDs that match the IDREFs from the first parameter. The result of this function is a sequence of elements, in document order with duplicates eliminated, containing the union of the collected element nodes from each string. An element node can be assigned an ID by means of an xml:id attribute or an attribute that is assigned the type ID by a DTD or xs:ID or any type derived from xs:ID by an XML schema, or the type model item property.

Example:

xf:id('X Y', instance('Z'))

Returns nodes identified by X or Y from the instance data document associated with the root element of the instance identified by Z.

Note:

This function is deprecated because it behaves the same as the fn:id() function defined in [Functions and Operators] and we recomend using fn:id().

Note:

When an ID is assigned to a attribute by asigning any type derived from xs:ID by an XML schema, or the type model item property that inform the ID type information is provided to the XPath data model. And consequently the is-id accessor will return true.

The context() Function

xf:context($id as xs:string?) as item()

This function returns the in-scope evaluation context item of an ancestor element of the node containing the XPath expression that invokes this function. The ancestor element is determined using the id parameter, taking into account Resolving ID References in XFormsXF. When the id parameter is omitted, the nearest ancestor element is used for determining the in-scopre evaluation context item to return. The ancestor element may have been created dynamically as part of the run-time expansion of repeated content as described in Section Resolving ID References in XFormsXF.

It is an error to specify a non existing id or an id of an element that isn't an ancestor.

Note:

If the resolved element isn't a binding element, see Evaluation ContextXF for obtaining the evaluation context for non binding elements.

Example:

<setvalue ref="x" value="xf:context()/y"/>

This action sets node x to the value of node y, where both nodes are children of the in-scope evaluation context node for the setvalue element.

Note:

An intended use of this function is in conjunction with the repeat element (Section The repeat ElementXF and the setvalue action element (Section The setvalue ElementXF). The intent is to provide form authors with a means of expressing a value attribute that is relative to the repeat context node when the Single Node Binding result is not.

The bind() Function

xf:bind($id as xs:string) as node()*

This function returns the sequence of nodes associated with the bind specified by the id parameter.

The id parameter is interpreted as an ID resolved as per Resolving ID References in XFormsXF, as if using the bind attribute. It is an error to specify a non existing bind ID.

If the function is used in a model binding expressionXF the XForms Processor should dispatch the event xforms-binding-error EventXF to the model.

Example:

<model>
  <instance>
    <data>
      <color>red</color>
      <color>blue</color>
      <color>green</color>
      <selected-color/>
    </data>
  </instance>
  <bind id="color-bind" ref="color"/>
  <bind id="selected-color-bind" ref="selected-color"/>
</model>
<repeat bind="color-bind" id="color-repeat">
  <output bind="color-bind">
    <label>Color:</label>
  </output>
  <trigger>
    <label>Select Color</label>
    <setvalue
      ev:event="DOMActivate"
      bind="selected-color-bind"
      value="bind('color-bind')[index('color-repeat')]"/>
  </trigger>
</repeat>
<output bind="selected-color-bind">
  <label>Selected Color:</label>
</output>

The setvalue action in this example is equivalent to writing:

<setvalue
  ev:event="DOMActivate"
  bind="selected-color-bind"
  value="context()"/>

Node Creation Functions

The element() Function

xf:element($qname as xs:anyAtomicType, $content as item()*) as element()

This function returns a new XML element with the qualified name provided. If the qualified name is not of type xs:QName the namespace of the element is resolved using the in-scope namespaces (the in-scope default namespace is used for qualified names that are unprefixed). The content argument is a sequence of items specifying attributes and content for the new element.

Examples:

xf:element('value')

Returns an empty element called "value" (in serialized form the result is <value/>).

xf:element('value', (xf:attribute('id', 'my-value'), 'John'))

Returns an element called "value" with an attribute "id" and text content "John" (in serialized form the result is <value id="my-value">John</value>).

xf:element('value', ('John', xf:attribute('id', 'my-value')))

This example illustrates that the attributes may be specified after the content of the element. The result is the same as the previous example (an element called "value" with an attribute "id" and text content "John").

The attribute() Function

xf:attribute($qname as xs:anyAtomicType, $value as xs:anyAtomicType?) as attribute()

This function returns a new XML attribute with the qualified name provided as first argument. If the qualified name is not of type xs:QName the namespace of the element is resolved using the in-scope namespaces (the in-scope default namespace is used for qualified names that are unprefixed). The second argument is an optional value for the attribute with the empty string as default.

Example:

xf:attribute('id', 'first-name')

Returns an attribute called "id" with a value of "first-name".


The parse() Function

xf:parse($arg as xs:string) as element()?

xf:parse($arg as xs:string, $format as xs:string) as element()?

This function takes as input a document represented as a string in $arg, and returns the XML document element node for the parsed document. The default if the $format is not specified, the XML 1.0 parsing is used. If $arg is the empty sequence or is not well-formed according to the $format parsing rules, the function returns the empty sequence.

The $format is a space-separated list of QNames intended to control various features of parsing, such as the grammar and grammatic variations, as well as allowing namespace qualified custom extensions.

Token Meaning
xml Parse input as XML 1.0
json Parse input as JSON data

Any other NCName

Reserved. Their use results in an exception (see 4 The XForms Function Library for the exception type)

QNameButNotNCName

An implementation-specific parser. If the implementation does not support the parser, then the empty sequence is returned.
<insert
  context="container/node"
  ref="elem"
  at="last()"
  position="after"
  origin="xf:parse('&lt;elem&gt; &lt;a/&gt; &lt;b/&gt; &lt;/elem&gt;')"/>

The function returns the document element node named elem, which is then used as the insert origin, i.e. the source node of the copy operation.

Note:

An important use case for this function is to convert unparsed data received by a form, such as from a submission, into parsed data.

Object Functions

The choose() Function

xf:choose($condition as xs:boolean, $choice-true as item()*, $choice-false as item()*) as item()*

This function provides a conditional test that chooses an object to return based on the boolean parameter. If the boolean parameter is true, then the first object is returned, otherwise the second object is returned. Each of the object parameters can be of any XPath datatype as described in Section DatatypesXF, and this function does no type conversion of the parameter it chooses to return.

Note:

All parameters of an XPath function are evaluated, so the parameter that is not returned by this function is still evaluated, and its result is discarded by this function.

Example:

xf:choose(count(x) > 0, x, y)

Returns the node-set of matching x if it is non-empty and the node-set matching y otherwise.

xf:choose(@x, @x, 0)

If the context node of the function contains attribute x, then the nodeset containing that attribute is returned. Otherwise, the number 0 is returned.

The event() Function

xf:event($property-name as xs:string) as item()*

Function event returns context specific information determined by the string argument. The returned context information is an XPath object whose type and content depends upon the requested property. Each event describes what properties can be accessed by this function and the type and value that will be returned as the result.

The event context properties available on each event are:

Property Type Value
type xs:string The name of the event.
bubbles xs:boolean Indicates whether or not an event is a bubbling event. If the event can bubble the value is true, else the value is false.
cancelable xs:boolean Indicates whether or not an event can have its default action prevented. If the default action can be prevented the value is true, else the value is false.
targetid xs:string? The id of the target to which the event was originally dispatched. If the target does not have an id an empty sequence is returned.
current-targetid xs:string? The id of the target whose EventListeners are currently being processed. If that target does not have an id an empty sequence is returned.
event-phase xs:string The current event phase: capture, target, or bubbling (When the event arrives at the target, the value is 'target'. Values capture and bubbling are as described in XML events)
time-stamp xs:integer? The time (in milliseconds relative to the epoch) at which the event was created. Due to the fact that some systems may not provide this information the value of timeStamp may be not available for all events. When not available, an empty sequence will be returned. Examples of epoch time are the time of the system start or 0:0:0 UTC 1st January 1970.

The event-specific context properties for each event type are provided in the sections that describe the events.

This function is intended for use in the XPath expressions of XForms actions. If invoked for any other XPath expression, such as a binding expression or model item property expression, this function returns the empty string. If this function is invoked from an XPath expression for an XForms action, then event context information is used from the most recently dispatched event whose action handler contains the XForms action.

Some properties defined for an event may be unavailable if certain prerequisite conditions were not met prior to the event being dispatched. Implementations may also add custom properties. If the event context information does not contain the property indicated by the string argument, then an empty node-set is returned.

Examples:

xf:event('inserted-nodes')

If called from an xforms-insert event handler, a nodeset is returned containing the instance data node or nodes inserted.

The eval() Function

xf:eval($expression as xs:string) as item()*

The function returns the result of evaluating the $expression in the context of the eval() function call. The expression containing the eval() function invocation references the XPath nodes referenced by the $expression, which introduces additional dependencies for the containing expression.

<model>
  <instance xmlns="">
    <data>
      <A>3</A>
      <B>4</B>
      <C value="power(../A * ../A + ../B * ../B, 0.5)">5</C>
    </data>
  </instance>
  <bind
    ref="descendant::*[@value]"
    calculate="xf:eval(@value)"/>
</model>

The model above responds to changes of data elements A and B by recalculating the value of C. For example, if A and B are changed to 5 and 12, then element C would be recalculated to the value 13. The model below is the same except that the expression in the value attribute is simplified due to the context change performed before the eval() function invocation.

<model>
  <instance xmlns="">
    <data>
      <A>3</A>
      <B>4</B>
      <C value="power(A * A + B * B, 0.5)">5</C>
    </data>
  </instance>
  <bind
    ref="descendant::*[@value]"
    calculate="../xf:eval(current()/@value)"/>
</model>

The eval-in-context() Function

xf:eval-in-context($expression as xs:string, $context as node()*) as item()*

The function returns the result of evaluating the $expression in the $context. The expression containing the eval() function invocation references the XPath nodes referenced by the $expression, which introduces additional dependencies for the containing expression. In XPath 2.0, the eval() function can be invoked later in an expression, after setting the desired context, so this function is included for ease of authoring and XPath 1.0 expression compatibility.

<model>
  <instance xmlns="">
    <data>
      <A>3</A>
      <B>4</B>
      <C value="power(A * A + B * B, 0.5)">5</C>
    </data>
  </instance>
  <bind
    ref="descendant::*[@value]"
    calculate="xf:eval-in-context(@value, ..)"/>
</model>

The model above responds to changes of data elements A and B by recalculating the value of C. For example, if A and B are changed to 5 and 12, then element C would be recalculated to the value 13. The expression in the value attribute is simplified, relative to a normal calculate expression, due to the context change provided by the second parameter.


URI Functions

The location-uri() Function

xf:location-uri() as xs:anyURI

The function returns a URL associated with the current XForms document. The URL should represent the location from which the current document has been loaded.

In a web browser environment, this function must return the same URL that the JavaScript Window.location function would return.

NOTE: If an implementation is not on the client, the fragment might not be returned.

xf:location-uri()

can return the value https://username:password@example.org/pages/order?id=42#content.

The location-param() Function

xf:location-param($name as xs:string) as xs:string*

The function returns the current location URL's parameter values for the given name, if any. It is equivalent to:

xf:uri-param-values(xf:uri-location(), $name)

The parameter values must be returned in the order they appear in the query. There can be more than one value if the parameter name appears more than once in the query.

The uri-scheme() Function

xf:uri-scheme($uri as xs:string) as xs:string?

The function returns the given URI's scheme or protocol if present.

xf:uri-scheme('https://username:password@example.org/pages/order?id=42#content')

returns https.

xf:uri-scheme('mailto:info@example.org')

returns mailto.

The uri-scheme-specific-part() Function

xf:uri-scheme-specific-part($uri as xs:string, $raw as xs:boolean) as xs:string?

The function returns the given URI's scheme-specific part if present. The scheme-specific part is the URI without its scheme, including the colon delimiter, and without its fragment, including the # character.

If $raw is true(), the escaped octets are not decoded. Otherwise, they are decoded.

xf:uri-scheme-specific-part('https://username:password@example.org/pages/order?id=42#content')

returns //username:password@example.org/pages/order?id=42.

xf:uri-scheme-specific-part('mailto:info@example.org')

returns info@example.org.

The uri-authority() Function

xf:uri-authority($uri as xs:string, $raw as xs:boolean) as xs:string?

For a hierarchical URI, the function returns the given URI's authority if present. The authority can include, for hierarchical URIs, user information, host, and port.

If $raw is true(), the escaped octets are not decoded. Otherwise, they are decoded.

xf:uri-authority('https://username:password@example.org/pages/order?id=42#content')

returns username:password@example.org.

xf:uri-authority('mailto:info@example.org')

returns the empty sequence as the URI is not hierarchical.

The uri-user-info() Function

xf:uri-user-info($uri as xs:string, $raw as xs:boolean) as xs:string?

For a hierarchical URI, the function returns the given URI's user info if present.

If $raw is true(), the escaped octets are not decoded. Otherwise, they are decoded.

xf:uri-user-info('https://username:password@example.org/pages/order?id=42#content')

returns username:password.

xf:uri-user-info('mailto:info@example.org')

returns the empty sequence as the URI is not hierarchical.

The uri-host() Function

xf:uri-host($uri as xs:string) as xs:string?

For a hierarchical URI, the function returns the given URI's host if present.

xf:uri-host('https://username:password@example.org/pages/order?id=42#content')

returns example.org.

xf:uri-host('mailto:info@example.org')

returns the empty sequence as the URI is not hierarchical.

The uri-port() Function

xf:uri-port($uri as xs:string) as xs:integer?

For a hierarchical URI, the function returns the given URI's port if present.

xf:uri-port('https://username:password@example.org/pages/order?id=42#content')

returns the empty sequence as not port is specified.

xf:uri-port('https://username:password@example.org:8080/pages/order?id=42#content')

returns the integer 8080.

xf:uri-port('mailto:info@example.org')

returns the empty sequence as the URI is not hierarchical.

The uri-path() Function

xf:uri-path($uri as xs:string, $raw as xs:boolean) as xs:string?

For a hierarchical URI, the function returns the given URI's path if present.

If $raw is true(), the escaped octets are not decoded. Otherwise, they are decoded.

xf:uri-path('https://username:password@example.org/pages/order?id=42#content')

returns /pages/order.

xf:uri-path('mailto:info@example.org')

returns the empty sequence as the URI is not hierarchical.

The uri-query() Function

xf:uri-query($uri as xs:string, $raw as xs:boolean) as xs:string?

For a hierarchical URI, the function returns the given URI's query if present.

If $raw is true(), the escaped octets are not decoded. Otherwise, they are decoded.

xf:uri-query('https://username:password@example.org/pages/order?id=42#content')

returns id=42.

xf:uri-query('mailto:info@example.org?subject=Hello')

returns the empty sequence as the URI is not hierarchical.

The uri-fragment() Function

xf:uri-fragment($uri as xs:string, $raw as xs:boolean) as xs:string?

The function returns the given URI's fragment if present.

If $raw is true(), the escaped octets are not decoded. Otherwise, they are decoded.

xf:uri-fragment('https://username:password@example.org/pages/order?id=42#content')

returns content.

xf:uri-fragment('mailto:info@example.org#ignored')

returns the empty sequence as the URI is not hierarchical.

The uri-param-names() Function

xf:uri-param-names($uri as xs:string) as xs:string*

The function returns the given URI's query parameter names, if present.

The parameter names must be returned in the order they appear in the query. Duplicates are possible, if a parameter name appears more than once.

xf:uri-param-names('https://example.org/?n1=v11&n2=v21&n1=v12&n2=v22')

returns the sequence 'n1', 'n2', 'n1', 'n2'. The XPath function distinct-values() can be used to obtain unique values:

distinct-values(xf:uri-param-names('https://example.org/?n1=v11&n2=v21&n1=v12&n2=v22'))

returns the sequence 'n1', 'n2'.

The uri-param-values() Function

xf:uri-param-values($uri as xs:string, $name as xs:string) as xs:string*

The function returns the given URI's parameter values for the given parameter name, if present.

The parameter values must be returned in the order they appear in the query. There can be more than one value if the parameter name appears more than once in the query.

xf:uri-param-values('https://example.org/?n1=v11&n2=v21&n1=v12&n2=v22', 'n1')

returns the sequence 'v11', 'v12'.

If the document was loaded from the location http://example.org/page?q=xforms, then:

xf:uri-param-values(xf:uri-location(), 'q')

returns xforms.

Extension Functions

See Extension FunctionsXF in XForms core.

References and Dependencies

Reference Selection

An XPath node is referenced by an expression if it is selected. A node is selected by matching an XPath NodeTest or by being returned by a function call. For examples, a node can match a name test, a wildcard test, a node type test, or it can be returned by or used as a parameter to a function, or it can appear in a filter expression (where all of the prior examples recursively apply).

The expression parameters of the eval() function and the eval-in-context() function) make references to XPath nodes and therefore introduce additional dependencies.

Additional dependencies for the computational dependency data structure

The index (The index() Function) and case (The case() Function) functions introduce additional dependencies for the computational dependency data structure. Beside the normal dependencies introduced by their arguments, these functions also need addtional dependencies to ensure that automatic recalculation happens when respectively the repeat index or selected case changes.

Implementation must behave as if each occurrence of a repeat is associated with an implicitly managed instance data node containing the repeat index. If a repeat identified as R1 contains a repeat identified as R2, then a repeat index instance node is managed for each occurrence of R2 that is generated by R1. An invocation of the function index() in an expression is considered to reference the repeat index instance node corresponding to the repeat index value that it returns. The same strategy should by used for the function case() (each occurrence of a switch is associated with an implicitly managed instance data node containing the ID of the selected case). An invocation of the function case() in an expression is considered to reference the switch instance node corresponding to the ID of the selected case that it returns. Note that if a switch is embedded in a repeat a seperate instance node (to track the ID of the selected case of the switch) should be created for every iteration in the repeat.

Error Indications

Error indications happen as a result of unusual conditions in the XForms Processor. Some of these are "fatal" errors, which halt processing, and bear the suffix "exception". Others are simply for notification, and bear the suffix "error". For all events in this section, it is permissible for the XForms Processor to perform some kind of default handling, for example logging error messages to a file.

The xforms-xpath-version-error Event

Dispatched as an indication of failure of the XPath version checks defined in the description of the xpath-version attribute in Section 2 The xpath-version attribute.

Target: the default model

Bubbles: Yes

Cancelable: Yes

Context Info:

Property Type Value
error-information string An implementation-specific error string

Default Action: Fatal error (halts processing).

Note:

This error occurs early in processing. XForms processors are not expected to product XForms user interface elements nor even execute XForms action handlers (such as a message action) in response to this event. This error is dispatched for the benefit of implementation-specific processing code that may be monitoring the behavior of an XForms processor.

Reserved Namespaces

[Definition: Definition: The XForms namespace, together with certain other namespaces recognized by an XForms processor, are classified as reserved namespaces and must be used only as specified in this and related specifications.] The reserved namespaces are those listed below.

Glossary Of Terms

Binding expression
[Definition: An [XPath 2.0] expression used in a binding.]
QNameButNotNCName
[Definition: A QName that is not an NCName. In 2006, the W3C named this a PrefixedName. ]
XPath 1.0 compatibility mode
[Definition: The term XPath 1.0 compatibility mode is defined in Section 2.1.1 Static ContextXP. This is a setting in the static context of an XPath expression; it has two values, true and false. When the value is set to true, the semantics of function calls and certain other operations are adjusted to give a greater degree of backwards compatibility between XPath 2.0 and XPath 1.0.]

References

Normative References

HMAC
RFC 2104 - HMAC: Keyed-Hashing for Message Authentication, H. Krawczyk, M. Bellare, R. Canetti, 1997. Available at http://www.ietf.org/rfc/rfc2104.txt
RFC 2119
RFC 2119: Key words for use in RFCs to Indicate Requirement Levels, S. Bradner, 1997. Available at http://www.ietf.org/rfc/rfc2119.txt.
SHA2
SECURE HASH STANDARD. FIPS PUB 180-2, August 2002. Available at http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
XML Events
XML Events - An events syntax for XML, Steven Pemberton, T. V. Raman, Shane P. McCarron, 2003. W3C Recommendation available at: http://www.w3.org/TR/2003/REC-xml-events-20031014/.
XHTML 1.0
XHTML 1.0: The Extensible HyperText Markup Language - A Reformulation of HTML 4 in XML 1.0, Steven Pemberton, et al., 2002. W3C Recommendation available at: http://www.w3.org/TR/2002/REC-xhtml1-20020801/.
XHTML Modularization
XHTML Modularization 1.1, D. Austin, S. Peruvemba, S. McCarron, M. Ishikawa, M. Birbeck, 2008. W3C Recommendation available at http://www.w3.org/TR/2008/REC-xhtml-modularization-20081008.
XPath 1.0
XML Path Language (XPath) Version 1.0, James Clark, Steve DeRose, 1999. W3C Recommendation available at: http://www.w3.org/TR/1999/REC-xpath-19991116/.
XPath 2.0
XML Path Language (XPath) 2.0, Anders Berglund, Scott Boag, Don Chamberlin, Mary F. Fernández, Michael Kay, Jonathan Robie, and Jérôme Siméon, 2007. W3C Recommendation available at: http://www.w3.org/TR/2007/REC-xpath20-20070123/.
Functions and Operators
XQuery 1.0 and XPath 2.0 Functions and Operators, Ashok Malhotra, Jim Melton, and Norman Walsh, Editors. World Wide Web Consortium, 23 Jan 2007.
Luhn Patent
Computer for Verifying Numbers, H. P. Luhn, U.S. Patent 2,950,048, 1960.
MD5
RFC 1321: The MD5 Message-Digest Algorithm, R. Rivest, 1992. Available at http://www.ietf.org/rfc/rfc1321.txt
XML 1.0
XML 1.0, Extensible Markup Language (XML) 1.0 (Fourth Edition), Tim Bray, Jean Paoli, C. M. Sperberg-McQueen, Eve Maler, 2008. W3C Recommendation available at: http://www.w3.org/TR/2008/REC-xml-20081126/.
XML 1.1
XML 1.1, Extensible Markup Language (XML) 1.1 (Second Edition), Tim Bray, Jean Paoli, C. M. Sperberg-McQueen, Eve Maler, François Yergeau, John Cowan, 2006. W3C Recommendation available at: http://www.w3.org/TR/2006/REC-xml11-20060816/.
XML Schema part 1
XML Schema Part 1: Structures, Henry S. Thompson, David Beech, Murray Maloney, Noah Mendelsohn, 2004. W3C Recommendation available at: http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/.
XML Schema part 2
XML Schema Part 2: Datatypes, Paul V. Biron, Ashok Malhotra, 2004. W3C Recommendation available at: http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/.
Unicode Collation Algorithm
Unicode Technical Standard #10, Unicode Collation Algorithm, Available at: http://www.unicode.org/unicode/reports/tr10/.
QNameButNotNCName
[Definition: A QName that is not an NCName. In 2006, the W3C named this a PrefixedName. ]

Informative References

EXSLT
EXSLT Web site. Available at http://www.exslt.org.


Acknowledgements (Non-Normative)

This document was produced with the participation of Forms Working Group participants, including:

  • John M. Boyer, IBM (Past Editor, Past Chair)
  • Erik Bruchez, Orbeon
  • Kurt Cagle, Invited expert
  • Alain Couthures, Invited expert
  • Philip Fennell, MarkLogic
  • Leigh L. Klotz, Jr., Xerox Corporation (Past Editor, Past Co-chair)
  • Ulrich Nicolas Lissé, DreamLab
  • Dan McCreary, Invited expert
  • Steven Pemberton, CWI (Chair)
  • T.V. Raman, Google
  • Sebastian Schnitzenbaumer
  • Nick Van den Bleeken, Inventive Designers n.v. (Past Editor)
  • Alessandro Vernet, Orbeon
  • Charles Wiecha, IBM

Production Notes (Non-Normative)

This document was created using an instance of MediaWiki. The sources were transformed to W3C format using a modified version of Sandro Hawke's revdoc.

<script src="//www.w3.org/scripts/TR/2016/fixup.js"></script>