If FC is not a partial function application:
If F's implementation is implementation-dependent (e.g., it is a built-in function or external function or host-language-dependent function, or a partial application of such a function):
F's implementation is invoked with the converted argument values using the contexts it is associated with in F. If these contexts are absent in F, it is associated with SC and DC.
The result is either an instance of F's return type or a dynamic error. This result is then the result of evaluating FC.
Errors raised by built-in functions are defined in [XQuery and XPath Functions and Operators 3.0].
Errors raised by external functions are implementation-defined (see 2.2.4 Consistency Constraints).
Errors raised by host-language-dependent functions are implementation-defined.
If F's implementation is a
FunctionBody
:
The FunctionBody
is evaluated. The dynamic context
for this evaluation is obtained by taking the dynamic context of
the InlineFunctionExpr
that
contains the FunctionBody
, and making the following
changes:
The focus (context item, context position, and context size) is absentDM30.
In the variable values component of the dynamic context, each converted argument value is bound to the corresponding parameter name.
When this is done, the converted
argument value retains its most specific dynamic type, even though this type may
be derived from the type of the formal parameter. For example, a
function with a parameter $p
of type
xs:decimal
can be invoked with an argument of type
xs:integer
, which is derived from
xs:decimal
. During the processing of this function
call, the dynamic type of $p
inside the
body of the function is considered to be
xs:integer
.
F's nonlocal variable bindings are also added to the variable values. (Note that the names of the nonlocal variables are by definition disjoint from the parameter names, so there can be no conflict.)
The value returned by evaluating the function body is then converted to the declared return type of F by applying the function conversion rules. The result is then the result of evaluating FC.
As with argument values, the value returned by a
function retains its most specific type, which may be derived from
the declared return type of F. For example, a function
that has a declared return type of xs:decimal
may in
fact return a value of dynamic type xs:integer
.
[Definition: The function conversion rules are used to convert an argument value to its expected type; that is, to the declared type of the function parameter. ] The expected type is expressed as a sequence type. The function conversion rules are applied to a given value as follows:
In a static function call, if XPath
1.0 compatibility mode is true
and an argument
of a static function is not of the expected type, then
the following conversions are applied sequentially to the argument
value V:
If the expected type calls for a single item or optional single
item (examples: xs:string
, xs:string?
,
xs:untypedAtomic
, xs:untypedAtomic?
,
node()
, node()?
, item()
,
item()?
), then the value V is effectively replaced by
V[1].
If the expected type is xs:string
or
xs:string?
, then the value V
is
effectively replaced by fn:string(V)
.
If the expected type is xs:double
or
xs:double?
, then the value V
is
effectively replaced by fn:number(V)
.
Note:
XPath 1.0 compatibility mode has no effect on dynamic function calls, converting the result of an inline function to its required type, partial function application, or implicit function calls that occur when evaluating functions such as fn:for-each and fn:filter.
If the expected type is a sequence of a generalized atomic type (possibly
with an occurrence indicator *
, +
, or
?
), the following conversions are applied:
Atomization is applied to the given value, resulting in a sequence of atomic values.
Each item in the atomic sequence that is of type
xs:untypedAtomic
is cast to the expected
generalized atomic type. For built-in
functions where the expected type is specified as numeric, arguments of type
xs:untypedAtomic
are cast to xs:double
.
If the item is of type xs:untypedAtomic
and the
expected type is namespace-sensitive, a type error [err:XPTY0117] is
raised.
For each numeric item in the atomic sequence that can be promoted to the expected atomic type using numeric promotion as described in B.1 Type Promotion, the promotion is done.
For each item of type xs:anyURI
in the atomic
sequence that can be promoted to the expected atomic type using
URI promotion as described in B.1 Type
Promotion, the promotion is done.
If the expected type is a TypedFunctionTest (possibly
with an occurrence indicator *
, +
, or
?
), function coercion is applied to
each function in the given value.
If, after the above conversions, the resulting value does not match the expected type according to the rules for SequenceType Matching, a type error is raised [err:XPTY0004]. Note that the rules for SequenceType Matching permit a value of a derived type to be substituted for a value of its base type.
Function coercion is a transformation applied to functionsDM30 during application of the function conversion rules. [Definition: Function coercion wraps a functionDM30 in a new function with signature the same as the expected type. This effectively delays the checking of the argument and return types until the function is invoked.]
Function coercion is only defined to operate on functionsDM30. Given a function F , and an expected function type, function coercion proceeds as follows: If F and the expected type have different arity, a type error is raised [err:XPTY0004]. Otherwise, coercion returns a new function with the following properties (as defined in Section 2.8.1 Functions DM30):
name: The name of F .
parameter names: The parameter names of F.
signature: Annotations
is
set to the annotations of F.
TypedFunctionTest
is set to the expected
type.
implementation: In effect, a
FunctionBody
that calls F, passing it the
parameters of this new function, in order.
nonlocal variable bindings: An empty mapping.
If the result of invoking the new function would necessarily result in a type error, that error may be raised during function coercion. It is implementation dependent whether this happens or not.
These rules have the following consequences:
SequenceType matching of the function's arguments and result are delayed until that function is invoked.
The function conversion rules applied to the function's arguments and result are defined by the SequenceType it has most recently been coerced to. Additional function conversion rules could apply when the wrapped function is invoked.
If an implementation has static type information about a function, that can be used to type check the function's argument and return types during static analysis.
For instance, consider the following query:
declare function local:filter($s as item()*, $p as function(xs:string) as xs:boolean) as item()* { $s[$p(.)] }; let $f := function($a) { starts-with($a, "E") } return local:filter(("Ethel", "Enid", "Gertrude"), $f)
The function $f
has a static type of
function(item()*) as item()*
. When the
local:filter()
function is called, the following
occurs to the function:
The function conversion rules result in applying function
coercion to $f
, wrapping $f in a new function ($p)
with the signature function(xs:string) as
xs:boolean
.
$p is matched against the SequenceType of
function(xs:string) as xs:boolean
, and succeeds.
When $p is invoked inside the predicate, function conversion and
SequenceType matching rules are applied to the context item
argument, resulting in an xs:string
value or a type
error.
$f is invoked with the xs:string
, which returns an
xs:boolean
.
$p applies function conversion rules to the result sequence from
$f, which already matches its declared return type of
xs:boolean
.
The xs:boolean
is returned as the result of $p.
Note:
Although the semantics of function coercion are specified in terms of wrapping the functions, static typing will often be able to reduce the number of places where this is actually necessary.
| [63] | NamedFunctionRef |
::= | EQName "#" IntegerLiteral |
| [94] | EQName |
::= | QName | URIQualifiedName |
[Definition: A named function reference denotes a named function.] [Definition: A named function is a function defined in the static context for the expression. To uniquely identify a particular named function, both its name as an expanded QName and its arity are required.]
If the EQName is a lexical QName that has no namespace prefix, it is considered to be in the default function namespace.
If the expanded QName and arity in a named function reference do not match the name and arity of a function signature in the static context, a static error is raised [err:XPST0017].
The value of a NamedFunctionRef
is the function
obtained by looking up the expanded QName and arity in the
named
functions component of the dynamic context.
Furthermore, if the function referenced by a
NamedFunctionRef
has an implementation-dependent
implementation, then the implementation of the function returned by
the NamedFunctionRef
is associated with the static
context of this NamedFunctionRef
expression and to the
dynamic context in which it is currently being evaluated.
Certain functions in the [XQuery and XPath Functions and Operators 3.0] specification are defined to be polymorphic. These are denoted as accepting parameters of "numeric" type, or returning "numeric" type. Here "numeric" is a pseudonym for the four primitive numeric types xs:decimal, xs:integer, xs:float, and xs:double. For the purposes of named function references, these functions are regarded as taking arguments and producing results of type xs:anyAtomicType, with a type error raised at runtime if the argument value provided is not of the correct numeric type.
Note:
The above way of modeling polymorphic functions is semantically backwards compatible with XPath 2.0. An implementation that supports static typing can choose to model the types of these functions more accurately if desired.
The following are examples of named function references:
fn:abs#1
references the fn:abs function which takes
a single argument.
fn:concat#5
references the fn:concat function which
takes 5 arguments.
local:myfunc#2
references a function named
local:myfunc which takes 2 arguments.
| [64] | InlineFunctionExpr |
::= | "function" "(" ParamList? ")" ("as" SequenceType)? FunctionBody |
| [2] | ParamList |
::= | Param ("," Param)* |
| [3] | Param |
::= | "$" EQName TypeDeclaration? |
| [66] | TypeDeclaration |
::= | "as" SequenceType |
| [5] | EnclosedExpr |
::= | "{" Expr "}" |
| [4] | FunctionBody |
::= | EnclosedExpr |
[Definition: An inline function expression creates an anonymous functionDM30 defined directly in the inline function expression itself.] An inline function expression specifies the names and SequenceTypes of the parameters to the function, the SequenceType of the result, and the body of the function.
If a function parameter is declared using a name but no type, its default type is item()*. If the result type is omitted from an inline function expression, its default result type is item()*.
The parameters of an inline function expression are considered to be variables whose scope is the function body. It is a static error [err:XQST0039] for an inline function expression to have more than one parameter with the same name.
The static context for the function body is inherited from the location of the inline function expression, with the exception of the static type of the context item which is initially absentDM30.
The variables in scope for the function body include all variables representing the function parameters, as well as all variables that are in scope for the inline function expression.
Note:
Function parameter names can mask variables that would otherwise be in scope for the function body.
The result of an inline function expression is a single function with the following properties (as defined in Section 2.8.1 Functions DM30):
name: Absent.
parameter names: The parameter names in the
InlineFunctionExpr
's ParamList
.
signature: A FunctionTest
constructed from the SequenceType
s in the
InlineFunctionExpr
.
implementation: The
InlineFunctionExpr
's
FunctionBody
.
nonlocal variable bindings: For each
nonlocal variable, a binding of it to its value in the variable values
component of the dynamic context of the
InlineFunctionExpr
.
The following are examples of some inline function expressions:
This example creates a function that takes no arguments and returns a sequence of the first 6 primes:
function() as xs:integer+ { 2, 3, 5, 7, 11, 13 }
This example creates a function that takes two xs:double arguments and returns their product:
function($a as xs:double, $b as xs:double) as xs:double { $a * $b }
This example creates a function that returns its item()* argument:
function($a) { $a }
This example creates a sequence of functions each of which returns a different node from the default collection.
collection()/(let $a := . return function() { $a })
| [48] | PostfixExpr |
::= | PrimaryExpr
(Predicate | ArgumentList)* |
| [51] | Predicate |
::= | "[" Expr "]" |
| [49] | ArgumentList |
::= | "(" (Argument (","
Argument)*)? ")" |
[Definition: An expression followed by a
predicate (that is, E1[E2]
) is referred to as a
filter expression: its effect is to return those items from
the value of E1
that satisfy the predicate in E2.]
Filter expressions are described in 3.2.1 Filter Expressions
An expression (other than a raw EQName) followed by an argument
list in parentheses (that is, E1(E2, E3, ...)
) is
referred to as a dynamic function
call . Its effect is to evaluate E1
to obtain a function, and then call that function, with
E2
, E3
, ...
as arguments.
Dynamic function calls are described in 3.2.2 Dynamic Function
Call .
| [48] | PostfixExpr |
::= | PrimaryExpr
(Predicate | ArgumentList)* |
| [51] | Predicate |
::= | "[" Expr "]" |
A filter expression consists of a base expression followed by a predicate, which is an expression written in square brackets. The result of the filter expression consists of the items returned by the base expression, filtered by applying the predicate to each item in turn. The ordering of the items returned by a filter expression is the same as their order in the result of the primary expression.
Note:
Where the expression before the square brackets is a ReverseStep or ForwardStep, the expression is technically not a filter expression but an AxisStep. There are minor differences in the semantics: see 3.3.3 Predicates within Steps
Here are some examples of filter expressions:
Given a sequence of products in a variable, return only those products whose price is greater than 100.
$products[price gt 100]
List all the integers from 1 to 100 that are divisible by 5.
(See 3.4.1 Constructing
Sequences for an explanation of the to
operator.)
(1 to 100)[. mod 5 eq 0]
The result of the following expression is the integer 25:
(21 to 29)[5]
The following example returns the fifth through ninth items in
the sequence bound to variable $orders
.
$orders[fn:position() = (5 to 9)]
The following example illustrates the use of a filter expression
as a step in a path expression.
It returns the last chapter or appendix within the book bound to
variable $book
:
$book/(chapter | appendix)[fn:last()]
For each item in the input sequence, the predicate expression is evaluated using an inner focus, defined as follows: The context item is the item currently being tested against the predicate. The context size is the number of items in the input sequence. The context position is the position of the context item within the input sequence.
For each item in the input sequence, the result of the predicate
expression is coerced to an xs:boolean
value, called
the predicate truth value, as described below. Those items
for which the predicate truth value is true
are
retained, and those for which the predicate truth value is
false
are discarded.
The predicate truth value is derived by applying the following rules, in order:
If the value of the predicate expression is a singleton atomic value of a
numeric type or derived
from a numeric type, the
predicate truth value is true
if the value of the
predicate expression is equal (by the eq
operator) to
the context position, and is false
otherwise.
[Definition: A predicate whose predicate
expression returns a numeric type is called a numeric
predicate.]
Otherwise, the predicate truth value is the effective boolean value of the predicate expression.
| [48] | PostfixExpr |
::= | PrimaryExpr
(Predicate | ArgumentList)* |
| [49] | ArgumentList |
::= | "(" (Argument (","
Argument)*)? ")" |
| [60] | Argument |
::= | ExprSingle |
ArgumentPlaceholder |
| [61] | ArgumentPlaceholder |
::= | "?" |
[Definition: A dynamic function call consists of a base expression that returns the function and a parenthesized list of zero or more arguments (argument expressions or ArgumentPlaceholders).]
A dynamic function call is evaluated as described in <IP_ADDRESS> Evaluating Static and Dynamic Function Calls .
The following are examples of some dynamic function calls:
This example invokes the function contained in $f, passing the arguments 2 and 3:
$f(2, 3)
This example fetches the second item from sequence $f, treats it
as a function and invokes it, passing an xs:string
argument:
$f[2]("Hi there")
This example invokes the function $f passing no arguments, and filters the result with a positional predicate:
$f()[2]
| [35] | PathExpr |
::= | ("/" RelativePathExpr?) |
| [36] | RelativePathExpr |
::= | StepExpr (("/" |
"//") StepExpr)* |
[Definition: A path expression can be
used to locate nodes within trees. A path expression consists of a
series of one or more steps,
separated by "/
" or "//
", and optionally
beginning with "/
" or "//
".] An initial
"/
" or "//
" is an abbreviation for one or
more initial steps that are implicitly added to the beginning of
the path expression, as described below.
A path expression consisting of a single step is evaluated as described in 3.3.2 Steps.
A "/
" at the beginning of a path expression is an
abbreviation for the initial step
(fn:root(self::node()) treat as
document-node())/
(however, if the "/
"
is the entire path expression, the trailing "/
" is
omitted from the expansion.) The effect of this initial step is to
begin the path at the root node of the tree that contains the
context node. If the context item is not a node, a type error is raised
[err:XPTY0020]. At
evaluation time, if the root node above the context node is not a
document node, a dynamic error is raised [err:XPDY0050].
A "//
" at the beginning of a path expression is an
abbreviation for the initial steps
(fn:root(self::node()) treat as
document-node())/descendant-or-self::node()/
(however, "//
" by itself is not a valid path
expression [err:XPST0003].) The effect of these initial
steps is to establish an initial node sequence that contains the
root of the tree in which the context node is found, plus all nodes
descended from this root. This node sequence is used as the input
to subsequent steps in the path expression. If the context item is
not a node, a type
error is raised [err:XPTY0020]. At evaluation time, if the root
node above the context node is not a document node, a dynamic error is
raised [err:XPDY0050].
Note:
The descendants of a node do not include attribute nodes or namespace nodes.
| [36] | RelativePathExpr |
::= | StepExpr (("/" |
"//") StepExpr)* |
Relative path expressions are binary operators on step
expressions, which are named E1
and E2
in
this section.
Each non-initial occurrence of "//
" in a path
expression is expanded as described in 3.3.5
Abbreviated Syntax, leaving a sequence of steps separated
by "/
" . This sequence of steps is then evaluated from
left to right. Each item produced by the evaluation of
E1
is used as the context item to evaluate E2
;
the sequences resulting from all the evaluations of E2
are combined to produce a result.
The following example illustrates the use of relative path expressions.
child::div1/child::para
Selects the para
element children of the
div1
element children of the context node; that is,
the para
element grandchildren of the context node
that have div1
parents.
Note:
Since each step in a path provides context nodes for the following step, in effect, only the last step in a path is allowed to return a sequence of non-nodes.
Note:
The "/
" character can be used
either as a complete path expression or as the beginning of a
longer path expression such as "/*
". Also,
"*
" is both the multiply operator and a wildcard in
path expressions. This can cause parsing difficulties when
"/
" appears on the left-hand side of "*
".
This is resolved using the leading-lone-slash constraint.
For example, "/*
" and "/ *
" are valid
path expressions containing wildcards, but "/*5
" and
"/ * 5
" raise syntax errors. Parentheses must be used
when "/
" is used on the left-hand side of an operator,
as in "(/) * 5
". Similarly, "4 + / * 5
"
raises a syntax error, but "4 + (/) * 5
" is a valid
expression. The expression "4 + /
" is also valid,
because /
does not occur on the left-hand side of the
operator.
Similarly, in the expression / union /*
, "union" is
interpreted as an element name rather than an operator. For it to
be parsed as an operator, the expression should be written
(/) union /*
.
/
)The path operator "/" is used to build expressions for locating nodes within trees. Its left-hand side expression must return a sequence of nodes. The operator returns either a sequence of nodes, in which case it additionally performs document ordering and duplicate elimination, or a sequence of non-nodes.
Each operation E1/E2
is evaluated as follows:
Expression E1
is evaluated, and if the result is not a
(possibly empty) sequence S
of nodes, a type error is raised
[err:XPTY0019].
Each node in S
then serves in turn to provide an inner
focus (the node as the context item, its position in S
as the context position, the length of S
as the
context size) for an evaluation of E2
, as described in
2.1.2 Dynamic Context. The
sequences resulting from all the evaluations of E2
are
combined as follows:
If every evaluation of E2
returns a (possibly
empty) sequence of nodes, these sequences are combined, and
duplicate nodes are eliminated based on node identity. The resulting node sequence is returned in document
order.
If every evaluation of E2
returns a (possibly
empty) sequence of non-nodes, these sequences are
concatenated, in order, and
returned.
If the multiple evaluations of E2
return at least
one node and at least one non-node, a type error is raised [err:XPTY0018].
Note:
The semantics of the path operator can also be defined using the
simple mapping operator as follows (forming the union with an empty
sequence ($R | ())
has the effect of eliminating
duplicates and sorting nodes into document order):
E1/E2 ::= let $R := E1!E2 return if (every $r in $R satisfies $r instance of node()) then ($R|()) else if (every $r in $R satisfies not($r instance of node())) then $R else error()
| [37] | StepExpr |
::= | PostfixExpr |
AxisStep |
| [38] | AxisStep |
::= | (ReverseStep |
ForwardStep) PredicateList |
| [39] | ForwardStep |
::= | (ForwardAxis
NodeTest) | AbbrevForwardStep |
| [42] | ReverseStep |
::= | (ReverseAxis
NodeTest) | AbbrevReverseStep |
| [50] | PredicateList |
::= | Predicate* |
[Definition: A step is a part of a path expression that generates a sequence of items and then filters the sequence by zero or more predicates. The value of the step consists of those items that satisfy the predicates, working from left to right. A step may be either an axis step or a postfix expression.] Postfix expressions are described in 3.2 Postfix Expressions.
[Definition: An axis step returns a sequence of nodes that are reachable from the context node via a specified axis. Such a step has two parts: an axis, which defines the "direction of movement" for the step, and a node test, which selects nodes based on their kind, name, and/or type annotation.] If the context item is a node, an axis step returns a sequence of zero or more nodes; otherwise, a type error is raised [err:XPTY0020]. The resulting node sequence is returned in document order. An axis step may be either a forward step or a reverse step, followed by zero or more predicates.
In the abbreviated syntax for a step, the axis can be omitted and other shorthand notations can be used as described in 3.3.5 Abbreviated Syntax.
The unabbreviated syntax for an axis step consists of the axis
name and node test separated by a double colon. The result of the
step consists of the nodes reachable from the context node via the
specified axis that have the node kind, name, and/or type annotation
specified by the node test. For example, the step
child::para
selects the para
element
children of the context node: child
is the name of the
axis, and para
is the name of the element nodes to be
selected on this axis. The available axes are described in <IP_ADDRESS> Axes. The available node tests are
described in <IP_ADDRESS> Node Tests.
Examples of steps are provided in 3.3.4
Unabbreviated Syntax and 3.3.5
Abbreviated Syntax.
| [40] | ForwardAxis |
::= | ("child" "::") |
| [43] | ReverseAxis |
::= | ("parent" "::") |
XPath defines a full set of axes for traversing documents, but a host language may define a subset of these axes. The following axes are defined:
The child
axis contains the children of the context
node, which are the nodes returned by the dm:children
accessor in [XQuery and XPath Data
Model (XDM) 3.0].
Note:
Only document nodes and element nodes have children. If the context node is any other kind of node, or if the context node is an empty document or element node, then the child axis is an empty sequence. The children of a document node or element node may be element, processing instruction, comment, or text nodes. Attribute, namespace, and document nodes can never appear as children.
the descendant
axis is defined as the transitive
closure of the child axis; it contains the descendants of the
context node (the children, the children of the children, and so
on)
the parent
axis contains the sequence returned by
the dm:parent
accessor in [XQuery and XPath Data Model (XDM) 3.0],
which returns the parent of the context node, or an empty sequence
if the context node has no parent
Note:
An attribute node may have an element node as its parent, even though the attribute node is not a child of the element node.
the ancestor
axis is defined as the transitive
closure of the parent axis; it contains the ancestors of the
context node (the parent, the parent of the parent, and so on)
Note:
The ancestor axis includes the root node of the tree in which the context node is found, unless the context node is the root node.
the following-sibling
axis contains the context
node's following siblings, those children of the context node's
parent that occur after the context node in document order; if
the context node is an attribute or
namespace node, the following-sibling
axis is
empty
the preceding-sibling
axis contains the context
node's preceding siblings, those children of the context node's
parent that occur before the context node in document order; if
the context node is an attribute or
namespace node, the preceding-sibling
axis is
empty
the following
axis contains all nodes that are
descendants of the root of the tree in which the context node is
found, are not descendants of the context node, and occur after the
context node in document order
the preceding
axis contains all nodes that are
descendants of the root of the tree in which the context node is
found, are not ancestors of the context node, and occur before the
context node in document order
the attribute
axis contains the attributes of the
context node, which are the nodes returned by the
dm:attributes
accessor in [XQuery and XPath Data Model (XDM) 3.0];
the axis will be empty unless the context node is an element
the self
axis contains just the context node
itself
the descendant-or-self
axis contains the context
node and the descendants of the context node
the ancestor-or-self
axis contains the context node
and the ancestors of the context node; thus, the ancestor-or-self
axis will always include the root node
the namespace
axis contains the namespace nodes of
the context node, which are the nodes returned by the
dm:namespace-nodes
accessor in [XQuery and XPath Data Model (XDM) 3.0];
this axis is empty unless the context node is an element node. The
namespace
axis is deprecated as of XPath
2.0. If XPath 1.0 compatibility mode is
true
, the namespace
axis must be
supported. If XPath 1.0 compatibility mode is
false
, then support for the namespace
axis is implementation-defined. An
implementation that does not support the namespace
axis when XPath 1.0 compatibility mode is
false
must raise a static error [err:XPST0010] if it is used. Applications
needing information about the in-scope namespaces of an element
should use the functions fn:in-scope-prefixes
and
fn:namespace-uri-for-prefix
defined in [XQuery and XPath Functions and Operators
3.0].
Axes can be categorized as forward axes and reverse axes. An axis that only ever contains the context node or nodes that are after the context node in document order is a forward axis. An axis that only ever contains the context node or nodes that are before the context node in document order is a reverse axis.
The parent
, ancestor
,
ancestor-or-self
, preceding
, and
preceding-sibling
axes are reverse axes; all other
axes are forward axes. The ancestor
,
descendant
, following
,
preceding
and self
axes partition a
document (ignoring attribute and
namespace nodes): they do not overlap and together they
contain all the nodes in the document.
[Definition: Every axis has a principal node kind. If an axis can contain elements, then the principal node kind is element; otherwise, it is the kind of nodes that the axis can contain.] Thus:
For the attribute axis, the principal node kind is attribute.
For the namespace axis, the principal node kind is namespace.
For all other axes, the principal node kind is element.
[Definition: A node test is a condition on the name, kind (element, attribute, text, document, comment, or processing instruction), and/or type annotation of a node. A node test determines which nodes contained by an axis are selected by a step.]
| [45] | NodeTest |
::= | KindTest | NameTest |
| [46] | NameTest |
::= | EQName | Wildcard |
| [47] | Wildcard |
::= | "*" |
| [94] | EQName |
::= | QName | URIQualifiedName |
[Definition: A node test that consists only of an
EQName or a Wildcard is called a name test.] A name test is
true if and only if the kind of the node is the principal node
kind for the step axis and the expanded QName of the node is equal (as
defined by the eq
operator) to the expanded QName
specified by the name test. For example, child::para
selects the para
element children of the context node;
if the context node has no para
children, it selects
an empty set of nodes. attribute::abc:href
selects the
attribute of the context node with the QName abc:href
;
if the context node has no such attribute, it selects an empty set
of nodes.
If the EQName is a lexical QName, it is resolved into an expanded QName using the statically known namespaces in the expression context. It is a static error [err:XPST0081] if the QName has a prefix that does not correspond to any statically known namespace. An unprefixed QName, when used as a name test on an axis whose principal node kind is element, has the namespace URI of the default element/type namespace in the expression context; otherwise, it has no namespace URI.
A name test is not satisfied by an element node whose name does not match the expanded QName of the name test, even if it is in a substitution group whose head is the named element.
A node test *
is true for any node of the principal node
kind of the step axis. For example, child::*
will
select all element children of the context node, and
attribute::*
will select all attributes of the context
node.
A node test can have the form NCName:*
. In this
case, the prefix is expanded in the same way as with a lexical QName, using the
statically known namespaces in the
static
context. If the prefix is not found in the statically known
namespaces, a static error is raised [err:XPST0081]. The node
test is true for any node of the principal node kind of the step
axis whose expanded QName has the namespace URI to
which the prefix is bound, regardless of the local part of the
name.
A node test can contain a BracedURILiteral, e.g.
Q{http://example.com/msg}*
Such a node test is true
for any node of the principal node kind of the step axis whose
expanded QName has the namespace URI specified in the
BracedURILiteral, regardless of the local part of the name.
A node test can also have the form *:NCName
. In
this case, the node test is true for any node of the principal node
kind of the step axis whose local name matches the given
NCName, regardless of its namespace or lack of a namespace.
[Definition: An alternative form of a node test called a kind test can select nodes based on their kind, name, and type annotation.] The syntax and semantics of a kind test are described in 2.5.4 SequenceType Syntax and 2.5.5 SequenceType Matching. When a kind test is used in a node test, only those nodes on the designated axis that match the kind test are selected. Shown below are several examples of kind tests that might be used in path expressions:
node()
matches any node.
text()
matches any text node.
comment()
matches any comment node.
namespace-node()
matches any namespace node.
element()
matches any element node.
schema-element(person)
matches any element node
whose name is person
(or is in the substitution
group headed by person
), and whose type annotation
is the same as (or is derived from) the declared type of the
person
element in the in-scope
element declarations.
element(person)
matches any element node whose name
is person
, regardless of its type annotation.
element(person, surgeon)
matches any non-nilled
element node whose name is person
, and whose type
annotation is surgeon
or is derived from
surgeon
.
element(*, surgeon)
matches any non-nilled element
node whose type annotation is surgeon
(or is derived
from surgeon
), regardless of its name.
attribute()
matches any attribute node.
attribute(price)
matches any attribute whose name
is price
, regardless of its type annotation.
attribute(*, xs:decimal)
matches any attribute
whose type annotation is xs:decimal
(or is derived
from xs:decimal
), regardless of its name.
document-node()
matches any document node.
document-node(element(book))
matches any document
node whose content consists of a single element node that satisfies
the kind test
element(book)
, interleaved with zero or more comments
and processing instructions.
| [38] | AxisStep |
::= | (ReverseStep |
ForwardStep) PredicateList |
| [50] | PredicateList |
::= | Predicate* |
| [51] | Predicate |
::= | "[" Expr "]" |
A predicate within a Step has similar syntax and semantics to a predicate within a filter expression. The only difference is in the way the context position is set for evaluation of the predicate.
For the purpose of evaluating the context position within a predicate, the input sequence is considered to be sorted as follows: into document order if the predicate is in a forward-axis step, into reverse document order if the predicate is in a reverse-axis step, or in its original order if the predicate is not in a step.
Here are some examples of axis steps that contain predicates:
This example selects the second chapter
element
that is a child of the context node:
child::chapter[2]
This example selects all the descendants of the context node
that are elements named "toy"
and whose
color
attribute has the value "red"
:
descendant::toy[attribute::color = "red"]
This example selects all the employee
children of
the context node that have both a secretary
child
element and an assistant
child element:
child::employee[secretary][assistant]
Note:
When using predicates with
a sequence of nodes selected using a reverse axis, it is
important to remember that the context positions for such a
sequence are assigned in reverse document order. For
example, preceding::foo[1]
returns the first
qualifying foo
element in reverse
document order, because the predicate is part of an axis step using a reverse
axis. By contrast, (preceding::foo)[1]
returns the
first qualifying foo
element in document order,
because the parentheses cause (preceding::foo)
to be
parsed as a primary expression in which context
positions are assigned in document order. Similarly,
ancestor::*[1]
returns the nearest ancestor element,
because the ancestor
axis is a reverse axis, whereas
(ancestor::*)[1]
returns the root element (first
ancestor in document order).
The fact that a reverse-axis step assigns context positions in reverse document order for the purpose of evaluating predicates does not alter the fact that the final result of the step is always in document order.
This section provides a number of examples of path expressions in which the axis is explicitly specified in each step. The syntax used in these examples is called the unabbreviated syntax. In many common cases, it is possible to write path expressions more concisely using an abbreviated syntax, as explained in 3.3.5 Abbreviated Syntax.
child::para
selects the para
element
children of the context node
child::*
selects all element children of the
context node
child::text()
selects all text node children of the
context node
child::node()
selects all the children of the
context node. Note that no attribute nodes are returned, because
attributes are not children.
attribute::name
selects the name
attribute of the context node
attribute::*
selects all the attributes of the
context node
parent::node()
selects the parent of the context
node. If the context node is an attribute node, this expression
returns the element node (if any) to which the attribute node is
attached.
descendant::para
selects the para
element descendants of the context node
ancestor::div
selects all div
ancestors of the context node
ancestor-or-self::div
selects the div
ancestors of the context node and, if the context node is a
div
element, the context node as well
descendant-or-self::para
selects the
para
element descendants of the context node and, if
the context node is a para
element, the context node
as well
self::para
selects the context node if it is a
para
element, and otherwise returns an empty
sequence
child::chapter/descendant::para
selects the
para
element descendants of the chapter
element children of the context node
child::*/child::para
selects all para
grandchildren of the context node
/
selects the root of the tree that contains the
context node, but raises a dynamic error if this root is not a
document node
/descendant::para
selects all the para
elements in the same document as the context node
/descendant::list/child::member
selects all the
member
elements that have a list
parent
and that are in the same document as the context node
child::para[fn:position() = 1]
selects the first
para
child of the context node
child::para[fn:position() = fn:last()]
selects the
last para
child of the context node
child::para[fn:position() = fn:last()-1]
selects
the last but one para
child of the context node
child::para[fn:position() > 1]
selects all the
para
children of the context node other than the first
para
child of the context node
following-sibling::chapter[fn:position() = 1]
selects the next chapter
sibling of the context
node
preceding-sibling::chapter[fn:position() = 1]
selects the previous chapter
sibling of the context
node
/descendant::figure[fn:position() = 42]
selects the
forty-second figure
element in the document containing
the context node
/child::book/child::chapter[fn:position() =
5]/child::section[fn:position() = 2]
selects the second
section
of the fifth chapter
of the
book
whose parent is the document node that contains
the context node
child::para[attribute::type eq "warning"]
selects
all para
children of the context node that have a
type
attribute with value warning
child::para[attribute::type eq 'warning'][fn:position() =
5]
selects the fifth para
child of the context
node that has a type
attribute with value
warning
child::para[fn:position() = 5][attribute::type eq
"warning"]
selects the fifth para
child of the
context node if that child has a type
attribute with
value warning
child::chapter[child::title = 'Introduction']
selects the chapter
children of the context node that
have one or more title
children whose typed value is equal to
the string Introduction
child::chapter[child::title]
selects the
chapter
children of the context node that have one or
more title
children
child::*[self::chapter or self::appendix]
selects
the chapter
and appendix
children of the
context node
child::*[self::chapter or self::appendix][fn:position() =
fn:last()]
selects the last chapter
or
appendix
child of the context node
| [41] | AbbrevForwardStep |
::= | "@"? NodeTest |
| [44] | AbbrevReverseStep |
::= | ".." |
The abbreviated syntax permits the following abbreviations:
The attribute axis attribute::
can be abbreviated
by @
. For example, a path expression
para[@type="warning"]
is short for
child::para[attribute::type="warning"]
and so selects
para
children with a type
attribute with
value equal to warning
.
If the axis name is omitted from an axis step, the default axis is
child
, with two exceptions: if the NodeTest in an axis step
contains an AttributeTest
or SchemaAttributeTest then the
default axis is attribute
; if the NodeTest in an axis step
is a NamespaceNodeTest then a
static error is raised [err:XQST0134] .
Note:
In an implementation that does not support the namespace axis, an attempt to access it always raises an error. Thus, an XQuery implementation will always raise an error in this case, since XQuery does not support the namespace axis. The namespace axis is deprecated as of XPath 2.0, but required in some languages that use XPath, including XSLT.
For example, the path expression section/para
is an
abbreviation for child::section/child::para
, and the
path expression section/@id
is an abbreviation for
child::section/attribute::id
. Similarly,
section/attribute(id)
is an abbreviation for
child::section/attribute::attribute(id)
. Note that the
latter expression contains both an axis specification and a
node test.
Each non-initial occurrence of //
is effectively
replaced by /descendant-or-self::node()/
during
processing of a path expression. For example,
div1//para
is short for
child::div1/descendant-or-self::node()/child::para
and
so will select all para
descendants of
div1
children.
Note:
The path expression //para[1]
does not
mean the same as the path expression
/descendant::para[1]
. The latter selects the first
descendant para
element; the former selects all
descendant para
elements that are the first
para
children of their respective parents.
A step consisting of ..
is short for
parent::node()
. For example, ../title
is
short for parent::node()/child::title
and so will
select the title
children of the parent of the context
node.
Note:
The expression .
, known as a context item
expression, is a primary expression, and is described
in 3.1.4 Context Item
Expression.
Here are some examples of path expressions that use the abbreviated syntax:
para
selects the para
element children
of the context node
*
selects all element children of the context
node
text()
selects all text node children of the
context node
@name
selects the name
attribute of
the context node
@*
selects all the attributes of the context
node
para[1]
selects the first para
child
of the context node
para[fn:last()]
selects the last para
child of the context node
*/para
selects all para
grandchildren
of the context node
/book/chapter[5]/section[2]
selects the second
section
of the fifth chapter
of the
book
whose parent is the document node that contains
the context node
chapter//para
selects the para
element
descendants of the chapter
element children of the
context node
//para
selects all the para
descendants of the root document node and thus selects all
para
elements in the same document as the context
node
//@version
selects all the version
attribute nodes that are in the same document as the context
node
//list/member
selects all the member
elements in the same document as the context node that have a
list
parent
.//para
selects the para
element
descendants of the context node
..
selects the parent of the context node
../@lang
selects the lang
attribute of
the parent of the context node
para[@type="warning"]
selects all para
children of the context node that have a type
attribute with value warning
para[@type="warning"][5]
selects the fifth
para
child of the context node that has a
type
attribute with value warning
para[5][@type="warning"]
selects the fifth
para
child of the context node if that child has a
type
attribute with value warning
chapter[title="Introduction"]
selects the
chapter
children of the context node that have one or
more title
children whose typed value is equal to the string
Introduction
chapter[title]
selects the chapter
children of the context node that have one or more
title
children
employee[@secretary and @assistant]
selects all the
employee
children of the context node that have both a
secretary
attribute and an assistant
attribute
book/(chapter|appendix)/section
selects every
section
element that has a parent that is either a
chapter
or an appendix
element, that in
turn is a child of a book
element that is a child of
the context node.
If E
is any expression that returns a sequence of
nodes, then the expression E/.
returns the same nodes
in document
order, with duplicates eliminated based on node identity.
XPath 3.0 supports operators to construct, filter, and combine
sequences of items. Sequences are never nested—for
example, combining the values 1
, (2, 3)
,
and ( )
into a single sequence results in the sequence
(1, 2, 3)
.
| [6] | Expr |
::= | ExprSingle (","
ExprSingle)* |
| [20] | RangeExpr |
::= | AdditiveExpr (
"to" AdditiveExpr
)? |
[Definition: One way to construct a sequence is by using the comma operator, which evaluates each of its operands and concatenates the resulting sequences, in order, into a single result sequence.] Empty parentheses can be used to denote an empty sequence.
A sequence may contain duplicate items, but a sequence is never an item in another sequence. When a new sequence is created by concatenating two or more input sequences, the new sequence contains all the items of the input sequences and its length is the sum of the lengths of the input sequences.
Note:
In places where the grammar calls for ExprSingle, such as the arguments of a function call, any expression that contains a top-level comma operator must be enclosed in parentheses.
Here are some examples of expressions that construct sequences:
The result of this expression is a sequence of five integers:
(10, 1, 2, 3, 4)
This expression combines four sequences of length one, two,
zero, and two, respectively, into a single sequence of length five.
The result of this expression is the sequence 10, 1, 2, 3,
4
.
(10, (1, 2), (), (3, 4))
The result of this expression is a sequence containing all
salary
children of the context node followed by all
bonus
children.
(salary, bonus)
Assuming that $price
is bound to the value
10.50
, the result of this expression is the sequence
10.50, 10.50
.
($price, $price)
A range expression can be used to construct a sequence of
consecutive integers. Each of the operands of the to
operator is converted as though it was an argument of a function
with the expected parameter type xs:integer?
. If
either operand is an empty sequence, or if the integer derived from
the first operand is greater than the integer derived from the
second operand, the result of the range expression is an empty
sequence. If the two operands convert to the same integer, the
result of the range expression is that integer. Otherwise, the
result is a sequence containing the two integer operands and every
integer between the two operands, in increasing order.
This example uses a range expression as one operand in
constructing a sequence. It evaluates to the sequence 10, 1,
2, 3, 4
.
(10, 1 to 4)
This example constructs a sequence of length one containing the
single integer 10
.
10 to 10
The result of this example is a sequence of length zero.
15 to 10
This example uses the fn:reverse
function to
construct a sequence of six integers in decreasing order. It
evaluates to the sequence 15, 14, 13, 12, 11, 10
.
fn:reverse(10 to 15)
| [23] | UnionExpr |
::= | IntersectExceptExpr (
("union" | "|") IntersectExceptExpr
)* |
| [24] | IntersectExceptExpr |
::= | InstanceofExpr
( ("intersect" | "except") InstanceofExpr )* |
XPath 3.0 provides the following operators for combining sequences of nodes:
The union
and |
operators are
equivalent. They take two node sequences as operands and return a
sequence containing all the nodes that occur in either of the
operands.
The intersect
operator takes two node sequences as
operands and returns a sequence containing all the nodes that occur
in both operands.
The except
operator takes two node sequences as
operands and returns a sequence containing all the nodes that occur
in the first operand but not in the second operand.
All these operators eliminate duplicate nodes from their result sequences based on node identity. The resulting sequence is returned in document order.
If an operand of union
, intersect
, or
except
contains an item that is not a node, a
type error is
raised [err:XPTY0004].
If an IntersectExceptExpr contains more than two InstanceofExprs, they are grouped from left to right. With a UnionExpr, it makes no difference how operands are grouped, the results are the same.
Here are some examples of expressions that combine sequences.
Assume the existence of three element nodes that we will refer to
by symbolic names A, B, and C. Assume that the variables
$seq1
, $seq2
and $seq3
are
bound to the following sequences of these nodes:
$seq1
is bound to (A, B)
$seq2
is bound to (A, B)
$seq3
is bound to (B, C)
Then:
$seq1 union $seq2
evaluates to the sequence (A,
B).
$seq2 union $seq3
evaluates to the sequence (A, B,
C).
$seq1 intersect $seq2
evaluates to the sequence (A,
B).
$seq2 intersect $seq3
evaluates to the sequence
containing B only.
$seq1 except $seq2
evaluates to the empty
sequence.
$seq2 except $seq3
evaluates to the sequence
containing A only.
In addition to the sequence operators described here, [XQuery and XPath Functions and Operators 3.0] includes functions for indexed access to items or sub-sequences of a sequence, for indexed insertion or removal of items in a sequence, and for removing duplicate items from a sequence.
XPath 3.0 provides arithmetic operators for addition, subtraction, multiplication, division, and modulus, in their usual binary and unary forms.
| [21] | AdditiveExpr |
::= | MultiplicativeExpr ( ("+" |
"-") MultiplicativeExpr
)* |
| [22] | MultiplicativeExpr |
::= | UnionExpr ( ("*" |
"div" | "idiv" | "mod") UnionExpr )* |
| [29] | UnaryExpr |
::= | ("-" | "+")* ValueExpr |
| [30] | ValueExpr |
::= | SimpleMapExpr |
A subtraction operator must be preceded by whitespace if it
could otherwise be interpreted as part of the previous token. For
example, a-b
will be interpreted as a name, but
a - b
and a -b
will be interpreted as
arithmetic expressions. (See A.2.4
Whitespace Rules for further details on whitespace
handling.)
If an AdditiveExpr contains more than two MultiplicativeExprs, they are grouped from left to right. So, for instance,
A - B + C - D
is equivalent to
((A - B) + C) - D
Similarly, the operands of a MultiplicativeExpr are grouped from left to right.
The first step in evaluating an arithmetic expression is to evaluate its operands. The order in which the operands are evaluated is implementation-dependent.
If XPath 1.0 compatibility mode is
true
, each operand is evaluated by applying the
following steps, in order:
Atomization is applied to the operand. The result of this operation is called the atomized operand.
If the atomized operand is an empty sequence, the result of the
arithmetic expression is the xs:double
value
NaN
, and the implementation need not evaluate the
other operand or apply the operator. However, an implementation may
choose to evaluate the other operand in order to determine whether
it raises an error.
If the atomized operand is a sequence of length greater than one, any items after the first item in the sequence are discarded.
If the atomized operand is now an instance of type
xs:boolean
, xs:string
,
xs:decimal
(including xs:integer
),
xs:float
, or xs:untypedAtomic
, then it is
converted to the type xs:double
by applying the
fn:number
function. (Note that fn:number
returns the value NaN
if its operand cannot be
converted to a number.)
If XPath 1.0 compatibility mode is
false
, each operand is evaluated by applying
the following steps, in order:
Atomization is applied to the operand. The result of this operation is called the atomized operand.
If the atomized operand is an empty sequence, the result of the arithmetic expression is an empty sequence, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error.
If the atomized operand is a sequence of length greater than one, a type error is raised [err:XPTY0004].
If the atomized operand is of type
xs:untypedAtomic
, it is cast to
xs:double
. If the cast fails, a dynamic error is
raised. [err:FORG0001]
After evaluation of the operands, if the types of the operands are a valid combination for the given arithmetic operator, the operator is applied to the operands, resulting in an atomic value or a dynamic error (for example, an error might result from dividing by zero.) The combinations of atomic types that are accepted by the various arithmetic operators, and their respective result types, are listed in B.2 Operator Mapping together with the operator functions that define the semantics of the operator for each type combination, including the dynamic errors that can be raised by the operator. The definitions of the operator functions are found in [XQuery and XPath Functions and Operators 3.0].
If the types of the operands, after evaluation, are not a valid combination for the given operator, according to the rules in B.2 Operator Mapping, a type error is raised [err:XPTY0004].
XPath 3.0 supports two division operators named div
and idiv
. Each of these operators accepts two operands
of any numeric type. As
described in [XQuery and XPath
Functions and Operators 3.0], $arg1 idiv $arg2
is
equivalent to ($arg1 div $arg2) cast as xs:integer?
except for error cases.
Here are some examples of arithmetic expressions:
The first expression below returns the xs:decimal
value -1.5
, and the second expression returns the
xs:integer
value -1
:
-3 div 2 -3 idiv 2
Subtraction of two date values results in a value of type
xs:dayTimeDuration
:
$emp/hiredate - $emp/birthdate
This example illustrates the difference between a subtraction operator and a hyphen:
$unit-price - $unit-discount
Unary operators have higher precedence than binary operators, subject of course to the use of parentheses. Therefore, the following two examples have different meanings:
-$bellcost + $whistlecost -($bellcost + $whistlecost)
Note:
Multiple consecutive unary arithmetic operators are permitted by XPath 3.0 for compatibility with [XML Path Language (XPath) Version 1.0].
| [19] | StringConcatExpr |
::= | RangeExpr ( "||"
RangeExpr )* |
String concatenation expressions allow the string
representations of values to be concatenated. In XPath 3.0,
$a || $b
is equivalent to fn:concat($a,
$b)
. The following expression evaluates to the string
concatenate
:
"con" || "cat" || "enate"
Comparison expressions allow two values to be compared. XPath 3.0 provides three kinds of comparison expressions, called value comparisons, general comparisons, and node comparisons.
| [18] | ComparisonExpr |
::= | StringConcatExpr ( (ValueComp |
| [32] | ValueComp |
::= | "eq" | "ne" | "lt" | "le" | "gt" | "ge" |
| [31] | GeneralComp |
::= | "=" | "!=" | "<" | "<=" | ">" |
">=" |
| [33] | NodeComp |
::= | "is" | "<<" | ">>" |
Note:
When an XPath expression is written within an XML
document, the XML escaping rules for special characters must be
followed; thus "<
" must be written as
"<
".
The value comparison operators are eq
,
ne
, lt
, le
, gt
,
and ge
. Value comparisons are used for comparing
single values.
The first step in evaluating a value comparison is to evaluate its operands. The order in which the operands are evaluated is implementation-dependent. Each operand is evaluated by applying the following steps, in order:
Atomization is applied to the operand. The result of this operation is called the atomized operand.
If the atomized operand is an empty sequence, the result of the value comparison is an empty sequence, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error.
If the atomized operand is a sequence of length greater than one, a type error is raised [err:XPTY0004].
If the atomized operand is of type
xs:untypedAtomic
, it is cast to
xs:string
.
Note:
The purpose of this rule is to make value comparisons
transitive. Users should be aware that the general comparison
operators have a different rule for casting of
xs:untypedAtomic
operands. Users should also be aware
that transitivity of value comparisons may be compromised by loss
of precision during type conversion (for example, two
xs:integer
values that differ slightly may both be
considered equal to the same xs:float
value because
xs:float
has less precision than
xs:integer
).
Next, if possible, the two operands are converted to their least
common type by a combination of type promotion and subtype
substitution. For example, if the operands are of type
hatsize
(derived from xs:integer
) and
shoesize
(derived from xs:float
), their
least common type is xs:float
.
Finally, if the types of the operands are a valid combination for the given operator, the operator is applied to the operands. The combinations of atomic types that are accepted by the various value comparison operators, and their respective result types, are listed in B.2 Operator Mapping together with the operator functions that define the semantics of the operator for each type combination. The definitions of the operator functions are found in [XQuery and XPath Functions and Operators 3.0].
Informally, if both atomized operands consist of exactly one
atomic value, then the result of the comparison is
true
if the value of the first operand is (equal, not
equal, less than, less than or equal, greater than, greater than or
equal) to the value of the second operand; otherwise the result of
the comparison is false
.
If the types of the operands, after evaluation, are not a valid combination for the given operator, according to the rules in B.2 Operator Mapping, a type error is raised [err:XPTY0004].
Here are some examples of value comparisons:
The following comparison atomizes the node(s) that are returned
by the expression $book/author
. The comparison is true
only if the result of atomization is the value "Kennedy" as an
instance of xs:string
or
xs:untypedAtomic
. If the result of atomization is an
empty sequence, the result of the comparison is an empty sequence.
If the result of atomization is a sequence containing more than one
value, a type error
is raised [err:XPTY0004].
$book1/author eq "Kennedy"
The following path expression contains a predicate that
selects products whose weight is greater than 100. For any product
that does not have a weight
subelement, the value of
the predicate is the empty sequence, and the product is not
selected. This example assumes that weight
is a
validated element with a numeric type.
//product[weight gt 100]
The following comparison is true if my:hatsize
and
my:shoesize
are both user-defined types that are
derived by restriction from a primitive numeric type:
my:hatsize(5) eq my:shoesize(5)
The following comparison is true. The eq
operator
compares two QNames by performing codepoint-comparisons of their
namespace URIs and their local names, ignoring their namespace
prefixes.
fn:QName("http://example.com/ns1", "this:color") eq fn:QName("http://example.com/ns1", "that:color")
The general comparison operators are =
,
!=
, <
, <=
,
>
, and >=
. General comparisons are
existentially quantified comparisons that may be applied to operand
sequences of any length. The result of a general comparison that
does not raise an error is always true
or
false
.
If XPath 1.0 compatibility mode is
true
, a general comparison is evaluated by applying
the following rules, in order:
If either operand is a single atomic value that is an instance
of xs:boolean
, then the other operand is converted to
xs:boolean
by taking its effective boolean
value.
Atomization is applied to each operand. After atomization, each operand is a sequence of atomic values.
If the comparison operator is <
,
<=
, >
, or >=
, then
each item in both of the operand sequences is converted to the type
xs:double
by applying the fn:number
function. (Note that fn:number
returns the value
NaN
if its operand cannot be converted to a
number.)
The result of the comparison is true
if and only if
there is a pair of atomic values, one in the first operand sequence
and the other in the second operand sequence, that have the
required magnitude relationship. Otherwise the result of the
comparison is false
. The magnitude relationship
between two atomic values is determined by applying the following
rules. If a cast
operation called for by these rules
is not successful, a dynamic error is raised. [err:FORG0001]
If at least one of the two atomic values is an instance of a
numeric type, then both
atomic values are converted to the type xs:double
by
applying the fn:number
function.
If at least one of the two atomic values is an instance of
xs:string
, or if both atomic values are instances of
xs:untypedAtomic
, then both atomic values are cast to
the type xs:string
.
If one of the atomic values is an instance of
xs:untypedAtomic
and the other is not an instance of
xs:string
, xs:untypedAtomic
, or any
numeric type, then the
xs:untypedAtomic
value is cast to the dynamic type of the
other value.
After performing the conversions described above, the atomic
values are compared using one of the value comparison operators
eq
, ne
, lt
, le
,
gt
, or ge
, depending on whether the
general comparison operator was =
, !=
,
<
, <=
, >
, or
>=
. The values have the required magnitude
relationship if and only if the result of this value comparison
is true
.
If XPath 1.0 compatibility mode is
false
, a general comparison is evaluated by
applying the following rules, in order:
Atomization is applied to each operand. After atomization, each operand is a sequence of atomic values.
The result of the comparison is true
if and only if
there is a pair of atomic values, one in the first operand sequence
and the other in the second operand sequence, that have the
required magnitude relationship. Otherwise the result of the
comparison is false
. The magnitude relationship
between two atomic values is determined by applying the following
rules. If a cast
operation called for by these rules
is not successful, a dynamic error is raised. [err:FORG0001]
If both atomic values are instances of
xs:untypedAtomic
, then the values are cast to the type
xs:string
.
If exactly one of the atomic values is an instance of
xs:untypedAtomic
, it is cast to a type depending on
the other value's dynamic type T according to the following rules,
in which V denotes the value to be cast:
If T is a numeric type or is derived from a numeric type, then V
is cast to xs:double
.
If T is xs:dayTimeDuration
or is derived from
xs:dayTimeDuration
, then V is cast to
xs:dayTimeDuration
.
If T is xs:yearMonthDuration
or is derived from
xs:yearMonthDuration
, then V is cast to
xs:yearMonthDuration
.
In all other cases, V is cast to the primitive base type of T.
Note:
The special treatment of the duration types is required to avoid
errors that may arise when comparing the primitive type
xs:duration
with any duration type.
After performing the conversions described above, the atomic
values are compared using one of the value comparison operators
eq
, ne
, lt
, le
,
gt
, or ge
, depending on whether the
general comparison operator was =
, !=
,
<
, <=
, >
, or
>=
. The values have the required magnitude
relationship if and only if the result of this value comparison
is true
.
When evaluating a general comparison in which either operand is
a sequence of items, an implementation may return true
as soon as it finds an item in the first operand and an item in the
second operand that have the required magnitude
relationship. Similarly, a general comparison may raise a
dynamic error
as soon as it encounters an error in evaluating either operand, or
in comparing a pair of items from the two operands. As a result of
these rules, the result of a general comparison is not
deterministic in the presence of errors.
Here are some examples of general comparisons:
The following comparison is true if the typed value of any author
subelement of $book1
is "Kennedy" as an instance of
xs:string
or xs:untypedAtomic
:
$book1/author = "Kennedy"
The following example contains three general comparisons. The
value of the first two comparisons is true
, and the
value of the third comparison is false
. This example
illustrates the fact that general comparisons are not
transitive.
(1, 2) = (2, 3) (2, 3) = (3, 4) (1, 2) = (3, 4)
The following example contains two general comparisons, both of
which are true
. This example illustrates the fact that
the =
and !=
operators are not inverses
of each other.
(1, 2) = (2, 3) (1, 2) != (2, 3)
Suppose that $a
, $b
, and
$c
are bound to element nodes with type annotation
xs:untypedAtomic
, with string values "1
",
"2
", and "2.0
" respectively. Then
($a, $b) = ($c, 3.0)
returns false
,
because $b
and $c
are compared as
strings. However, ($a, $b) = ($c, 2.0)
returns
true
, because $b
and 2.0
are
compared as numbers.
Node comparisons are used to compare two nodes, by their identity or by their document order. The result of a node comparison is defined by the following rules:
The operands of a node comparison are evaluated in implementation-dependent order.
If either operand is an empty sequence, the result of the comparison is an empty sequence, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error.
Each operand must be either a single node or an empty sequence; otherwise a type error is raised [err:XPTY0004].
A comparison with the is
operator is
true
if the two operand nodes have the same identity,
and are thus the same node; otherwise it is false
. See
[XQuery and XPath Data Model (XDM)
3.0] for a definition of node identity.
A comparison with the <<
operator returns
true
if the left operand node precedes the right
operand node in document order; otherwise it returns
false
.
A comparison with the >>
operator returns
true
if the left operand node follows the right
operand node in document order; otherwise it returns
false
.
Here are some examples of node comparisons:
The following comparison is true only if the left and right sides each evaluate to exactly the same single node:
/books/book[isbn="1558604820"] is /books/book[call="QA76.9 C3845"]
The following comparison is true only if the node identified by the left side occurs before the node identified by the right side in document order:
/transactions/purchase[parcel="28-451"] << /transactions/sale[parcel="33-870"]
A logical expression is either an and-expression
or an or-expression. If a logical expression does not raise
an error, its value is always one of the boolean values
true
or false
.
| [16] | OrExpr |
::= | AndExpr ( "or"
AndExpr )* |
| [17] | AndExpr |
::= | ComparisonExpr
( "and" ComparisonExpr
)* |
The first step in evaluating a logical expression is to find the effective boolean value of each of its operands (see 2.4.3 Effective Boolean Value).
The value of an and-expression is determined by the effective boolean values (EBV's) of its operands, as shown in the following table:
| AND: | EBV2 = true |
EBV2 = false |
error in EBV2 |
EBV1 = true |
true |
false |
error |
EBV1 = false |
false |
false |
if XPath 1.0 compatibility mode is
true , then false ; otherwise either
false or error. |
| error in EBV1 | error | if XPath 1.0 compatibility mode is
true , then error; otherwise either false
or error. |
error |
The value of an or-expression is determined by the effective boolean values (EBV's) of its operands, as shown in the following table:
| OR: | EBV2 = true |
EBV2 = false |
error in EBV2 |
EBV1 = true |
true |
true |
if XPath 1.0 compatibility mode is
true , then true ; otherwise either
true or error. |
EBV1 = false |
true |
false |
error |
| error in EBV1 | if XPath 1.0 compatibility mode is
true , then error; otherwise either true
or error. |
error | error |
If XPath 1.0 compatibility mode is
true
, the order in which the operands of a logical
expression are evaluated is effectively prescribed. Specifically,
it is defined that when there is no need to evaluate the second
operand in order to determine the result, then no error can occur
as a result of evaluating the second operand.
If XPath 1.0 compatibility mode is
false
, the order in which the operands of a logical
expression are evaluated is implementation-dependent.
In this case, an or-expression can return true
if the first expression evaluated is true, and it can raise an
error if evaluation of the first expression raises an error.
Similarly, an and-expression can return false
if the
first expression evaluated is false, and it can raise an error if
evaluation of the first expression raises an error. As a result of
these rules, a logical expression is not deterministic in the
presence of errors, as illustrated in the examples below.
Here are some examples of logical expressions:
The following expressions return true
:
1 eq 1 and 2 eq 2
1 eq 1 or 2 eq 3
The following expression may return either false
or
raise a dynamic
error (in XPath
1.0 compatibility mode, the result must be
false
):
1 eq 2 and 3 idiv 0 = 1
The following expression may return either true
or
raise a dynamic
error (in XPath
1.0 compatibility mode, the result must be
true
):
1 eq 1 or 3 idiv 0 = 1
The following expression must raise a dynamic error:
1 eq 1 and 3 idiv 0 = 1
In addition to and- and or-expressions, XPath 3.0 provides a
function named fn:not
that takes a general sequence as
parameter and returns a boolean value. The fn:not
function is defined in [XQuery and
XPath Functions and Operators 3.0]. The fn:not
function reduces its parameter to an effective boolean
value. It then returns true
if the effective
boolean value of its parameter is false
, and
false
if the effective boolean value of its parameter
is true
. If an error is encountered in finding the
effective boolean value of its operand, fn:not
raises
the same error.
XPath provides an iteration facility called a for expression.
| [8] | ForExpr |
::= | SimpleForClause "return"
ExprSingle |
| [9] | SimpleForClause |
::= | "for" SimpleForBinding ("," SimpleForBinding)* |
| [10] | SimpleForBinding |
::= | "$" VarName "in"
ExprSingle |
A for
expression is evaluated as follows:
If the for
expression uses multiple variables, it
is first expanded to a set of nested for
expressions,
each of which uses only one variable. For example, the expression
for $x in X, $y in Y return $x + $y
is expanded to
for $x in X return for $y in Y return $x + $y
.
In a single-variable for
expression, the variable
is called the range variable, the value of the expression
that follows the in
keyword is called the binding
sequence, and the expression that follows the
return
keyword is called the return expression.
The result of the for
expression is obtained by
evaluating the return
expression once for each item in
the binding sequence, with the range variable bound to that item.
The resulting sequences are concatenated (as if by the comma operator) in
the order of the items in the binding sequence from which they were
derived.
The following example illustrates the use of a
for
expression in restructuring an input document. The
example is based on the following input:
<bib> <book> <title>TCP/IP Illustrated</title> <author>Stevens</author> <publisher>Addison-Wesley</publisher> </book> <book> <title>Advanced Programming in the Unix Environment</title> <author>Stevens</author> <publisher>Addison-Wesley</publisher> </book> <book> <title>Data on the Web</title> <author>Abiteboul</author> <author>Buneman</author> <author>Suciu</author> </book> </bib>
The following example transforms the input document into a list
in which each author's name appears only once, followed by a list
of titles of books written by that author. This example assumes
that the context item is the bib
element in the input
document.
for $a in fn:distinct-values(book/author)
return ((book/author[. = $a])[1], book[author = $a]/title)
The result of the above expression consists of the following
sequence of elements. The titles of books written by a given author
are listed after the name of the author. The ordering of
author
elements in the result is implementation-dependent due to
the semantics of the fn:distinct-values
function.
<author>Stevens</author> <title>TCP/IP Illustrated</title> <title>Advanced Programming in the Unix environment</title> <author>Abiteboul</author> <title>Data on the Web</title> <author>Buneman</author> <title>Data on the Web</title> <author>Suciu</author> <title>Data on the Web</title>
The following example illustrates a for
expression
containing more than one variable:
for $i in (10, 20),
$j in (1, 2)
return ($i + $j)
The result of the above expression, expressed as a sequence of
numbers, is as follows: 11, 12, 21, 22
The scope of a variable bound in a for
expression
comprises all subexpressions of the for
expression
that appear after the variable binding. The scope does not include
the expression to which the variable is bound. The following
example illustrates how a variable binding may reference another
variable bound earlier in the same for
expression:
for $x in $z, $y in f($x)
return g($x, $y)
Note:
The focus for evaluation of the return
clause of a
for
expression is the same as the focus for evaluation
of the for
expression itself. The following example,
which attempts to find the total value of a set of order-items, is
therefore incorrect:
fn:sum(for $i in order-item return @price * @qty)
Instead, the expression must be written to use the variable
bound in the for
clause:
fn:sum(for $i in order-item return $i/@price * $i/@qty)
XPath allows a variable to be declared and bound to a value using a let expression.
| [11] | LetExpr |
::= | SimpleLetClause "return"
ExprSingle |
| [12] | SimpleLetClause |
::= | "let" SimpleLetBinding ("," SimpleLetBinding)* |
| [13] | SimpleLetBinding |
::= | "$" VarName ":="
ExprSingle |
A let expression is evaluated as follows:
If the let expression uses multiple variables, it is first
expanded to a set of nested let expressions, each of which uses
only one variable. For example, the expression let $x := 4,
$y := 3 return $x + $y
is expanded to let $x := 4
return let $y := 3 return $x + $y
.
In a single-variable let expression, the variable is called the
range variable, the value of the expression that follows the
:=
symbol is called the binding sequence, and the
expression that follows the return keyword is called the return
expression. The result of the let expression is obtained by
evaluating the return expression with the range variable bound to
the binding sequence.
The scope of a variable bound in a let expression comprises all subexpressions of the let expression that appear after the variable binding. The scope does not include the expression to which the variable is bound. The following example illustrates how a variable binding may reference another variable bound earlier in the same let expression:
let $x := doc('a.xml')/*, $y := $x//* return $y[@value gt $x/@min]
XPath 3.0 supports a conditional expression based on the
keywords if
, then
, and
else
.
| [15] | IfExpr |
::= | "if" "(" Expr ")" "then"
ExprSingle "else" ExprSingle |
The expression following the if
keyword is called
the test expression, and the expressions following the
then
and else
keywords are called the
then-expression and else-expression,
respectively.
The first step in processing a conditional expression is to find the effective boolean value of the test expression, as defined in 2.4.3 Effective Boolean Value.
The value of a conditional expression is defined as follows: If
the effective boolean value of the test expression is
true
, the value of the then-expression is returned. If
the effective boolean value of the test expression is
false
, the value of the else-expression is
returned.
Conditional expressions have a special rule for propagating
dynamic
errors. If the effective value of the test expression is
true
, the conditional expression ignores (does not
raise) any dynamic errors encountered in the else-expression. In
this case, since the else-expression can have no observable effect,
it need not be evaluated. Similarly, if the effective value of the
test expression is false
, the conditional expression
ignores any dynamic errors encountered in the
then-expression, and the then-expression need not be evaluated.
Here are some examples of conditional expressions:
In this example, the test expression is a comparison expression:
if ($widget1/unit-cost < $widget2/unit-cost) then $widget1 else $widget2
In this example, the test expression tests for the existence of
an attribute named discounted
, independently of its
value:
if ($part/@discounted) then $part/wholesale else $part/retail
Quantified expressions support existential and universal
quantification. The value of a quantified expression is always
true
or false
.
| [14] | QuantifiedExpr |
::= | ("some" | "every") "$" VarName "in" ExprSingle ("," "$" VarName "in" ExprSingle)* "satisfies" ExprSingle |
A quantified expression begins with a quantifier,
which is the keyword some
or every
,
followed by one or more in-clauses that are used to bind variables,
followed by the keyword satisfies
and a test
expression. Each in-clause associates a variable with an expression
that returns a sequence of items, called the binding sequence for
that variable. The in-clauses generate tuples of variable bindings,
including a tuple for each combination of items in the binding
sequences of the respective variables. Conceptually, the test
expression is evaluated for each tuple of variable bindings.
Results depend on the effective boolean value of the test expressions, as
defined in 2.4.3 Effective Boolean
Value. The value of the quantified expression is defined by
the following rules:
If the quantifier is some
, the quantified
expression is true
if at least one evaluation of the
test expression has the effective boolean value true
; otherwise
the quantified expression is false
. This rule implies
that, if the in-clauses generate zero binding tuples, the value of
the quantified expression is false
.
If the quantifier is every
, the quantified
expression is true
if every evaluation of the test
expression has the effective boolean value true
; otherwise
the quantified expression is false
. This rule implies
that, if the in-clauses generate zero binding tuples, the value of
the quantified expression is true
.
The scope of a variable bound in a quantified expression comprises all subexpressions of the quantified expression that appear after the variable binding. The scope does not include the expression to which the variable is bound.
The order in which test expressions are evaluated for the
various binding tuples is implementation-dependent. If the
quantifier is some
, an implementation may return
true
as soon as it finds one binding tuple for which
the test expression has an effective boolean value of true
, and it
may raise a dynamic error as soon as it finds one
binding tuple for which the test expression raises an error.
Similarly, if the quantifier is every
, an
implementation may return false
as soon as it finds
one binding tuple for which the test expression has an effective boolean
value of false
, and it may raise a dynamic error as soon
as it finds one binding tuple for which the test expression raises
an error. As a result of these rules, the value of a quantified
expression is not deterministic in the presence of errors, as
illustrated in the examples below.
Here are some examples of quantified expressions:
This expression is true
if every part
element has a discounted
attribute (regardless of the
values of these attributes):
every $part in /parts/part satisfies $part/@discounted
This expression is true
if at least one
employee
element satisfies the given comparison
expression:
some $emp in /emps/employee satisfies ($emp/bonus > 0.25 * $emp/salary)
In the following examples, each quantified expression evaluates
its test expression over nine tuples of variable bindings, formed
from the Cartesian product of the sequences (1, 2, 3)
and (2, 3, 4)
. The expression beginning with
some
evaluates to true
, and the
expression beginning with every
evaluates to
false
.
some $x in (1, 2, 3), $y in (2, 3, 4) satisfies $x + $y = 4
every $x in (1, 2, 3), $y in (2, 3, 4) satisfies $x + $y = 4
This quantified expression may either return true
or raise a type
error, since its test expression returns true
for
one variable binding and raises a type error for another:
some $x in (1, 2, "cat") satisfies $x * 2 = 4
This quantified expression may either return false
or raise a type
error, since its test expression returns false
for
one variable binding and raises a type error for another:
every $x in (1, 2, "cat") satisfies $x * 2 = 4
sequence
types are used in instance of
, cast
,
castable
, and treat
expressions.
| [25] | InstanceofExpr |
::= | TreatExpr (
"instance" "of" SequenceType )? |
The boolean operator instance of
returns
true
if the value of its first operand matches the
SequenceType in its second
operand, according to the rules for SequenceType matching; otherwise it
returns false
. For example:
5 instance of xs:integer
This example returns true
because the given value
is an instance of the given type.
5 instance of xs:decimal
This example returns true
because the given value
is an integer literal, and xs:integer
is derived by
restriction from xs:decimal
.
(5, 6) instance of xs:integer+
This example returns true
because the given
sequence contains two integers, and is a valid instance of the
specified type.
. instance of element()
This example returns true
if the context item is an
element node or false
if the context item is defined
but is not an element node. If the context item is absentDM30,
a dynamic
error is raised [err:XPDY0002].
| [28] | CastExpr |
::= | UnaryExpr ( "cast"
"as" SingleType
)? |
| [65] | SingleType |
::= | SimpleTypeName
"?"? |
| [70] | AtomicOrUnionType |
::= | EQName |
Occasionally it is necessary to convert a value to a specific
datatype. For this purpose, XPath 3.0 provides a cast
expression that creates a new value of a specific type based on an
existing value. A cast
expression takes two operands:
an input expression and a target type. The type of
the atomized value of the input expression is called
the input type. The SimpleTypeName must be the name of
a type defined in the in-scope schema types, and it must be a
simple type [err:XQST0052]. In addition, the target
type cannot be xs:NOTATION
,
xs:anySimpleType
, or
xs:anyAtomicType
[err:XPST0080]. The optional occurrence indicator
"?
" denotes that an empty sequence is permitted. If
the target type is a lexical QName that has no
namespace prefix, it is considered to be in the default
element/type namespace.
Casting a node to xs:QName
can cause
surprises because it uses the static context of the cast
expression to provide the namespace bindings for this operation.
Instead of casting to xs:QName
, it is generally
preferable to use the fn:QName
function, which
allows the namespace context to be taken from the document
containing the QName.
The semantics of the cast
expression are as
follows:
The input expression is evaluated.
The result of the first step is atomized.
If the result of atomization is a sequence of more than one atomic value, a type error is raised [err:XPTY0004].
If the result of atomization is an empty sequence:
If ?
is specified after the target type, the result
of the cast
expression is an empty sequence.
If ?
is not specified after the target type, a
type error is
raised [err:XPTY0004].
If the result of atomization is a single atomic value, the result of the cast expression depends on the input type and the target type. In general, the cast expression attempts to create a new value of the target type based on the input value. Only certain combinations of input type and target type are supported. A summary of the rules are listed below—the normative definition of these rules is given in [XQuery and XPath Functions and Operators 3.0]. For the purpose of these rules, an implementation may determine that one type is derived by restriction from another type either by examining the in-scope schema definitions or by using an alternative, implementation-dependent mechanism such as a data dictionary.
cast
is supported for the combinations of input
type and target type listed in
Section 18.1 Casting from primitive types to primitive types
FO30. For each of these combinations,
both the input type and the target type are primitive schema types. For example,
a value of type xs:string
can be cast into the schema
type xs:decimal
. For each of these built-in
combinations, the semantics of casting are specified in [XQuery and XPath Functions and Operators
3.0].
cast
is supported if the input type is a
non-primitive atomic type that is derived by restriction from the
target type. In this case, the input value is mapped into the value
space of the target type, unchanged except for its type. For
example, if shoesize
is derived by restriction from
xs:integer
, a value of type shoesize
can
be cast into the schema type xs:integer
.
cast
is supported if the target type is a
non-primitive atomic type and the input type is
xs:string
or xs:untypedAtomic
. The input
value is first converted to a value in the lexical space of the
target type by applying the whitespace normalization rules for the
target type (as defined in [XML Schema
1.0] or [XML Schema 1.1]). The
lexical value is then converted to the value space of the target
type using the schema-defined rules for the target type. If the
input value fails to satisfy some facet of the target type, a
dynamic error
may be raised as specified in [XQuery
and XPath Functions and Operators 3.0].
cast
is supported to any target type if the input
type is xs:string
or xs:untypedAtomic
.
The target type may be an atomic type, a union type, or a list
type. The semantics are based on the rules for validation in
[XML Schema 1.0] or [XML Schema 1.1].
The effect of casting a string S to a simple type T is the same as constructing an element or attribute node whose string value is S, validating it using T as the governing type, and atomizing the resulting node. The result may be a single atomic value or (if list types are involved) a sequence of zero or more atomic values.
If the target type is namespace-sensitive, then the namespace bindings in the static context will be used to resolve any namespace prefix found in the supplied string.
cast
is supported if the target type is a
non-primitive atomic type that is derived by restriction from the
input type. The input value must satisfy all the facets of the
target type (in the case of the pattern facet, this is checked by
generating a string representation of the input value, using the
rules for casting to xs:string
). The resulting value
is the same as the input value, but with a different dynamic type.
If a primitive type P1 can be cast into a primitive type P2, then any type derived by restriction from P1 can be cast into any type derived by restriction from P2, provided that the facets of the target type are satisfied. First the input value is cast to P1 using rule (b) above. Next, the value of type P1 is cast to the type P2, using rule (a) above. Finally, the value of type P2 is cast to the target type, using rule (d) above.
For any combination of input type and target type that is not in
the above list, a cast
expression raises a type error [err:XPTY0004].
If casting from the input type to the target type is supported
but nevertheless it is not possible to cast the input value into
the value space of the target type, a dynamic error is raised.
[err:FORG0001] This includes the case when any facet of the target
type is not satisfied. For example, the expression
"2003-02-31" cast as xs:date
would raise a dynamic error.
| [27] | CastableExpr |
::= | CastExpr ( "castable"
"as" SingleType
)? |
| [65] | SingleType |
::= | SimpleTypeName
"?"? |
XPath 3.0 provides an expression that tests whether a given
value is castable into a given target type. The
SimpleTypeName must be the name of a type defined in the in-scope schema
types, and the type must be simple
[err:XQST0052]. In
addition, the target type cannot be xs:NOTATION
xs:anySimpleType
, or
xs:anyAtomicType
[err:XPST0080]. The optional occurrence indicator
"?
" denotes that an empty sequence is permitted.
The expression E castable as T
returns
true
if the result of evaluating E
can be
successfully cast into the target type T
by using a
cast
expression; otherwise it returns
false
. If evaluation of E
fails with a
dynamic error, the castable
expression as a whole
fails. The castable
expression can be used as a
predicate to avoid errors at
evaluation time. It can also be used to select an appropriate type
for processing of a given value, as illustrated in the following
example:
if ($x castable as hatsize) then $x cast as hatsize else if ($x castable as IQ) then $x cast as IQ else $x cast as xs:string
For every generalized atomic type in the
in-scope schema
types (except xs:NOTATION
and
xs:anyAtomicType
, which are not instantiable), a
constructor function is implicitly defined. In each case,
the name of the constructor function is the same as the name of its
target type (including namespace). The signature of the constructor
function for type T is as follows:
T($arg as xs:anyAtomicType?) as T?
[Definition: The constructor
function for a given type is used to convert instances of other
atomic types into the given type. The semantics of the constructor
function call T($arg)
are defined to be equivalent to
the expression (($arg) cast as T?)
.]
The following examples illustrate the use of constructor functions:
This example is equivalent to ("2000-01-01" cast as
xs:date?)
.
xs:date("2000-01-01")
This example is equivalent to (($floatvalue * 0.2E-5) cast
as xs:decimal?)
.
xs:decimal($floatvalue * 0.2E-5)
This example returns an xs:dayTimeDuration
value
equal to 21 days. It is equivalent to ("P21D" cast as
xs:dayTimeDuration?)
.
xs:dayTimeDuration("P21D")
If usa:zipcode
is a user-defined atomic type in the
in-scope schema
types, then the following expression is equivalent to the
expression ("12345" cast as usa:zipcode?)
.
usa:zipcode("12345")
Note:
An instance of an atomic type that is not in a namespace can be constructed in either of the following ways:
By using a cast
expression, if the default
element/type namespace is absentDM30.
17 cast as apple
By using a constructor function, if the default function namespace is absentDM30.
apple(17)
| [26] | TreatExpr |
::= | CastableExpr (
"treat" "as" SequenceType
)? |
XPath 3.0 provides an expression called treat
that
can be used to modify the static type of its operand.
Like cast
, the treat
expression takes
two operands: an expression and a SequenceType. Unlike
cast
, however, treat
does not change the
dynamic type or
value of its operand. Instead, the purpose of treat
is
to ensure that an expression has an expected dynamic type at
evaluation time.
The semantics of expr1
treat
as
type1
are as follows:
During static analysis:
The static
type of the treat
expression is
type1
. This enables the expression to be
used as an argument of a function that requires a parameter of
type1
.
During expression evaluation:
If expr1
matches
type1
, using the rules for SequenceType matching, the
treat
expression returns the value of
expr1
; otherwise, it raises a dynamic error
[err:XPDY0050]. If
the value of expr1
is returned, its identity
is preserved. The treat
expression ensures that the
value of its expression operand conforms to the expected type at
run-time.
Example:
$myaddress treat as element(*, USAddress)
The static
type of $myaddress
may be element(*,
Address)
, a less specific type than element(*,
USAddress)
. However, at run-time, the value of
$myaddress
must match the type element(*,
USAddress)
using rules for SequenceType matching;
otherwise a dynamic error is raised [err:XPDY0050].
!
)| [34] | SimpleMapExpr |
::= | PathExpr ("!"
PathExpr)* |
The simple map operator "!
" is used for simple
mappings. Both its left-hand side expression and its
right-hand-side expression may return a mixed sequence of nodes and
non-nodes.
Each operation E1!E2
is evaluated as follows:
Expression E1
is evaluated to a sequence
S
. Each item in S
then serves in turn to
provide an inner focus (the item as the context item, its position
in S
as the context position, the length of
S
as the context size) for an evaluation of
E2
in the dynamic context. The sequences resulting
from all the evaluations of E2
are combined as
follows: Every evaluation of E2
returns a (possibly
empty) sequence of items. These sequences are concatenated and
returned. If ordering mode is ordered, the returned sequence
preserves the orderings within and among the subsequences generated
by the evaluations of E2
; otherwise the order of the
returned sequence is implementation-dependent.
Simple map operators have functionality similar to <IP_ADDRESS> Path operator (/). The following table summarizes the differences between these two operators
| Operator | Path operator (E1 / E2 ) |
Simple map operator (E1 ! E2 ) |
|---|---|---|
| E1 | Any sequence of nodes | Any sequence of items |
| E2 | Either a sequence of nodes or a sequence of non-node items | A sequence of items |
| Additional processing | Duplicate elimination and document ordering | Simple sequence concatenation |
The following examples illustrate the use of simple map operators combined with path expressions.
child::div1 / child::para / string() ! concat("id-",
.)
Selects the para
element children of the
div1
element children of the context node; that is,
the para
element grandchildren of the context node
that have div1
parents. It then outputs the strings
obtained by prepending "id-"
to each of the string
values of these grandchildren.
$emp ! (@first, @middle, @last)
Returns the values of the attributes first
,
middle
, and last
for element
$emp
, in the order given. (The /
operator
here returns the attributes in an unpredictable order.)
$docs ! ( //employee)
Returns all the employees within all the documents identified by the variable docs, in document order within each document, but retaining the order of documents.
avg( //employee / salary ! translate(., '$', '') !
number(.))
Returns the average salary of the employees, having converted
the salary to a number by removing any $
sign and then
converting to a number. (The second occurrence of !
could not be written as /
because the left-hand
operand of /
cannot be an atomic value.)
The grammar of XPath 3.0 uses the same simple Extended Backus-Naur Form (EBNF) notation as [XML 1.0] with the following minor differences.
All named symbols have a name that begins with an uppercase letter.
It adds a notation for referring to productions in external specs.
Comments or extra-grammatical constraints on grammar productions are between '/*' and '*/' symbols.
A 'xgc:' prefix is an extra-grammatical constraint, the details of which are explained in A.1.2 Extra-grammatical Constraints
A 'ws:' prefix explains the whitespace rules for the production, the details of which are explained in A.2.4 Whitespace Rules
A 'gn:' prefix means a 'Grammar Note', and is meant as a clarification for parsing rules, and is explained in A.1.3 Grammar Notes. These notes are not normative.
The terminal symbols for this grammar include the quoted strings used in the production rules below, and the terminal symbols defined in section A.2.1 Terminal Symbols.
The EBNF notation is described in more detail in A.1.1 Notation.
To increase readability, the EBNF in the main body of this document omits some of these notational features. This appendix is the normative version of the EBNF.
The following definitions will be helpful in defining precisely this exposition.
[Definition: Each rule in the grammar defines one symbol, using the following format:
symbol ::= expression
]
[Definition: A terminal is a symbol or string or pattern that can appear in the right-hand side of a rule, but never appears on the left-hand side in the main grammar, although it may appear on the left-hand side of a rule in the grammar for terminals.] The following constructs are used to match strings of one or more characters in a terminal:
matches any Char with a value in the range(s) indicated (inclusive).
matches any Char with a value among the characters enumerated.
matches any Char with a value not among the characters given.
matches the sequence of characters that appear inside the double quotes.
matches the sequence of characters that appear inside the single quotes.
matches any string matched by the production defined in the external specification as per the provided reference.
Patterns (including the above constructs) can be combined with grammatical operators to form more complex patterns, matching more complex sets of character strings. In the examples that follow, A and B represent (sub-)patterns.
A
is treated as a unit and may be combined as
described in this list.
matches A
or nothing; optional A
.
matches A
followed by B
. This operator
has higher precedence than alternation; thus A B | C D
is identical to (A B) | (C D)
.
matches A
or B
but not both.
matches any string that matches A
but does not
match B
.
matches one or more occurrences of A
. Concatenation
has higher precedence than alternation; thus A+ | B+
is identical to (A+) | (B+)
.
matches zero or more occurrences of A
.
Concatenation has higher precedence than alternation; thus A*
| B*
is identical to (A*) | (B*)
This section contains constraints on the EBNF productions, which are required to parse syntactically valid sentences. The notes below are referenced from the right side of the production, with the notation: /* xgc: <id> */.
Constraint: leading-lone-slash
A single slash may appear either as a complete path expression
or as the first part of a path expression in which it is followed
by a RelativePathExpr.
In some cases, the next token after the slash is insufficient to
allow a parser to distinguish these two possibilities: the
*
token and keywords like union
could be
either an operator or a NameTest . For example, without
lookahead the first part of the expression / * 5
is
easily taken to be a complete expression, / *
, which
has a very different interpretation (the child nodes of
/
).
Therefore to reduce the need for lookahead, if the token immediately following a slash can form the start of a RelativePathExpr, then the slash must be the beginning of a PathExpr, not the entirety of it.
A single slash may be used as the left-hand argument of an
operator by parenthesizing it: (/) * 5
. The expression
5 * /
, on the other hand, is syntactically valid
without parentheses.
The version of XML and XML Names (e.g. [XML
1.0] and [XML Names], or [XML 1.1] and [XML Names
1.1]) is implementation-defined. It is
recommended that the latest applicable version be used (even if it
is published later than this specification). The EBNF in this
specification links only to the 1.0 versions. Note also that these
external productions follow the whitespace rules of their
respective specifications, and not the rules of this specification,
in particular A.2.4.1
Default Whitespace Handling. Thus prefix :
localname
is not a syntactically valid lexical QName for purposes of
this specification, just as it is not permitted in a XML document.
Also, comments are not permissible on either side of the colon.
Also extra-grammatical constraints such as well-formedness
constraints must be taken into account.
XPath expressions allow any legal XML Unicode character, subject only to constraints imposed by the host language.
Constraint: reserved-function-names
Unprefixed function names spelled the same way as language
keywords could make the language harder to recognize. For instance,
if(foo)
could be taken either as a FunctionCall or as the beginning of
an IfExpr. Therefore, an
unprefixed function name must not be any of the names in A.3 Reserved Function Names.
A function named "if" can be called by binding its namespace to a prefix and using the prefixed form: "library:if(foo)" instead of "if(foo)".
Constraint: occurrence-indicators
As written, the grammar in A XPath 3.0 Grammar is ambiguous for some forms using the '+' and '*' Kleene operators. The ambiguity is resolved as follows: these operators are tightly bound to the SequenceType expression, and have higher precedence than other uses of these symbols. Any occurrence of '+' and '*', as well as '?', following a sequence type is assumed to be an occurrence indicator, which binds to the last ItemType in the SequenceType.
Thus, 4 treat as item() + - 5
must be interpreted
as (4 treat as item()+) - 5
, taking the '+' as an
OccurrenceIndicator and the '-' as a subtraction operator. To force
the interpretation of "+" as an addition operator (and the
corresponding interpretation of the "-" as a unary minus),
parentheses may be used: the form (4 treat as item()) +
-5
surrounds the SequenceType expression with
parentheses and leads to the desired interpretation.
function () as xs:string *
is interpreted as
function () as (xs:string *)
, not as (function
() as xs:string) *
. Parentheses can be used as shown to
force the latter interpretation.
This rule has as a consequence that certain forms which would otherwise be syntactically valid and unambiguous are not recognized: in "4 treat as item() + 5", the "+" is taken as an OccurrenceIndicator, and not as an operator, which means this is not a syntactically valid expression.
This section contains general notes on the EBNF productions, which may be helpful in understanding how to interpret and implement the EBNF. These notes are not normative. The notes below are referenced from the right side of the production, with the notation: /* gn: <id> */.
Note:
Look-ahead is required to distinguish FunctionCall from a EQName or
keyword followed by a Comment.
For example: address (: this may be empty :)
may be
mistaken for a call to a function named "address" unless this
lookahead is employed. Another example is for (: whom the
bell :) $tolls in 3 return $tolls
, where the keyword "for"
must not be mistaken for a function name.
Comments are allowed everywhere that ignorable whitespace is allowed, and the Comment symbol does not explicitly appear on the right-hand side of the grammar (except in its own production). See A.2.4.1 Default Whitespace Handling.
A comment can contain nested comments, as long as all "(:" and ":)" patterns are balanced, no matter where they occur within the outer comment.
Note:
Lexical analysis may typically handle nested comments by incrementing a counter for each "(:" pattern, and decrementing the counter for each ":)" pattern. The comment does not terminate until the counter is back to zero.
Some illustrative examples:
(: commenting out a (: comment :) may be confusing, but
often helpful :)
is a syntactically valid Comment, since
balanced nesting of comments is allowed.
"this is just a string :)"
is a syntactically valid
expression. However, (: "this is just a string :)" :)
will cause a syntax error. Likewise, "this is another string
(:"
is a syntactically valid expression, but (: "this
is another string (:" :)
will cause a syntax error. It is a
limitation of nested comments that literal content can cause
unbalanced nesting of comments.
for (: set up loop :) $i in $x return $i
is
syntactically valid, ignoring the comment.
5 instance (: strange place for a comment :) of
xs:integer
is also syntactically valid.
The terminal symbols assumed by the grammar above are described in this section.
Quoted strings appearing in production rules are terminal symbols.
Other terminal symbols are defined in A.2.1 Terminal Symbols.
Some productions are defined by reference to the XML and XML Names specifications (e.g. [XML 1.0] and [XML Names], or [XML 1.1] and [XML Names 1.1] . A host language may choose which version of these specifications is used; it is recommended that the latest applicable version be used (even if it is published later than this specification).
When tokenizing, the longest possible match that is consistent with the EBNF is used.
All keywords are case sensitive. Keywords are not reserved—that is, any lexical QName may duplicate a keyword except as noted in A.3 Reserved Function Names.
| [95] | IntegerLiteral |
::= | Digits |
|
| [96] | DecimalLiteral |
::= | ("." Digits) |
(Digits "." [0-9]*) |
/* ws: explicit */ |
| [97] | DoubleLiteral |
::= | (("." Digits) |
(Digits ("." [0-9]*)?)) [eE]
[+-]? Digits |
/* ws: explicit */ |
| [98] | StringLiteral |
::= | ('"' (EscapeQuot |
[^"])* '"') | ("'" (EscapeApos | [^'])* "'") |
/* ws: explicit */ |
| [99] | URIQualifiedName |
::= | BracedURILiteral NCName |
/* ws: explicit */ |
| [100] | BracedURILiteral |
::= | "Q" "{" [^{}]* "}" |
/* ws: explicit */ |
| [101] | EscapeQuot |
::= | '""' |
|
| [102] | EscapeApos |
::= | "''" |
|
| [103] | Comment |
::= | "(:" (CommentContents | Comment)* ":)" |
/* ws: explicit */ |
| /* gn: comments */ | ||||
| [104] | QName |
::= | [http://www.w3.org/TR/REC-xml-names/#NT-QName]Names |
/* xgc: xml-version */ |
| [105] | NCName |
::= | [http://www.w3.org/TR/REC-xml-names/#NT-NCName]Names |
/* xgc: xml-version */ |
| [106] | Char |
::= | [http://www.w3.org/TR/REC-xml#NT-Char]XML |
/* xgc: xml-version */ |
The following symbols are used only in the definition of terminal symbols; they are not terminal symbols in the grammar of A.1 EBNF.
| [107] | Digits |
::= | [0-9]+ |
| [108] | CommentContents |
::= | (Char+ - (Char* ('(:' |
':)') Char*)) |
XPath 3.0 expressions consist of terminal symbols and symbol separators.
Terminal symbols that are not used exclusively in /* ws: explicit */ productions are of two kinds: delimiting and non-delimiting.
[Definition: The delimiting terminal symbols are: "!", "!=", StringLiteral, "#", "$", "(", ")", "*", "+", (comma), "-", (dot), "..", "/", "//", (colon), "::", ":=", "<", "<<", "<=", "=", ">", ">=", ">>", "?", "@", BracedURILiteral, "[", "]", "{", "|", "||", "}" ]
[Definition: The non-delimiting terminal symbols are: IntegerLiteral, URIQualifiedName, NCName, DecimalLiteral, DoubleLiteral, QName, "ancestor", "ancestor-or-self", "and", "as", "attribute", "cast", "castable", "child", "comment", "descendant", "descendant-or-self", "div", "document-node", "element", "else", "empty-sequence", "eq", "every", "except", "following", "following-sibling", "for", "function", "ge", "gt", "idiv", "if", "in", "instance", "intersect", "is", "item", "le", "let", "lt", "mod", "namespace", "namespace-node", "ne", "node", "of", "or", "parent", "preceding", "preceding-sibling", "processing-instruction", "return", "satisfies", "schema-attribute", "schema-element", "self", "some", "text", "then", "to", "treat", "union" ]
[Definition: Whitespace and Comments function as symbol separators. For the most part, they are not mentioned in the grammar, and may occur between any two terminal symbols mentioned in the grammar, except where that is forbidden by the /* ws: explicit */ annotation in the EBNF, or by the /* xgc: xml-version */ annotation.]
It is customary to separate consecutive terminal symbols by whitespace and Comments, but this is required only when otherwise two non-delimiting symbols would be adjacent to each other. There are two exceptions to this, that of "." and "-", which do require a symbol separator if they follow a QName or NCName. Also, "." requires a separator if it precedes or follows a numeric literal.
The host language must specify whether the XPath 3.0 processor normalizes all line breaks on input, before parsing, and if it does so, whether it uses the rules of [XML 1.0] or [XML 1.1].
For [XML 1.0] processing, all of the following must be translated to a single #xA character:
the two-character sequence #xD #xA
any #xD character that is not immediately followed by #xA.
For [XML 1.1] processing, all of the following must be translated to a single #xA character:
the two-character sequence #xD #xA
the two-character sequence #xD #x85
the single character #x85
the single character #x2028
any #xD character that is not immediately followed by #xA or #x85.
[Definition: A whitespace character is any of the characters defined by [http://www.w3.org/TR/REC-xml/#NT-S].]
[Definition: Ignorable whitespace consists of any whitespace characters that may occur between terminals, unless these characters occur in the context of a production marked with a ws:explicit annotation, in which case they can occur only where explicitly specified (see A.2.4.2 Explicit Whitespace Handling).] Ignorable whitespace characters are not significant to the semantics of an expression. Whitespace is allowed before the first terminal and after the last terminal of an XPath. Whitespace is allowed between any two terminals. Comments may also act as "whitespace" to prevent two adjacent terminals from being recognized as one. Some illustrative examples are as follows:
foo- foo
results in a syntax error. "foo-" would be
recognized as a QName.
foo -foo
is syntactically equivalent to foo -
foo
, two QNames separated by a subtraction operator.
foo(: This is a comment :)- foo
is syntactically
equivalent to foo - foo
. This is because the comment
prevents the two adjacent terminals from being recognized as
one.
foo-foo
is syntactically equivalent to single
QName. This is because "-" is a valid character in a QName. When
used as an operator after the characters of a name, the "-" must be
separated from the name, e.g. by using whitespace or
parentheses.
10div 3
results in a syntax error.
10 div3
also results in a syntax error.
10div3
also results in a syntax error.
Explicit whitespace notation is specified with the EBNF productions, when it is different from the default rules, using the notation shown below. This notation is not inherited. In other words, if an EBNF rule is marked as /* ws: explicit */, the notation does not automatically apply to all the 'child' EBNF productions of that rule.
/* ws: explicit */ means that the EBNF notation explicitly
notates, with S
or otherwise, where whitespace characters are
allowed. In productions with the /* ws: explicit */ annotation,
A.2.4.1 Default Whitespace
Handling does not apply. Comments are also not allowed in these
productions.
The following names are not allowed as function names in an unprefixed form because expression syntax takes precedence.
attribute
comment
document-node
element
empty-sequence
function
if
item
namespace-node
node
processing-instruction
schema-attribute
schema-element
switch
text
typeswitch
Note:
Although the keywords switch
and
typeswitch
are not used in XPath, they are considered
reserved function names for compatibility with XQuery.
The grammar in A.1 EBNF normatively defines built-in precedence among the operators of XQuery. These operators are summarized here to make clear the order of their precedence from lowest to highest. The associativity column indicates the order in which operators of equal precedence in an expression are applied.
| # | Operator | Associativity |
|---|---|---|
| 1 | , (comma) | either |
| 2 | for, let, some, every, if | NA |
| 3 | or | either |
| 4 | and | either |
| 5 | eq, ne, lt, le, gt, ge, =, !=, <, <=, >, >=, is, <<, >> | NA |
| 6 | || | left-to-right |
| 7 | to | NA |
| 8 | +, - (binary) | left-to-right |
| 9 | *, div, idiv, mod | left-to-right |
| 10 | union, | | either |
| 11 | intersect, except | left-to-right |
| 12 | instance of | NA |
| 13 | treat as | NA |
| 14 | castable as | NA |
| 15 | cast as | NA |
| 16 | -, + (unary) | right-to-left |
| 17 | ! | left-to-right |
| 18 | /, // | left-to-right |
| 19 | [ ] | left-to-right |
In the "Associativity" column, "either" indicates that all the
operators at that level have the associative property (i.e.,
(A op B) op C
is equivalent to A op (B op
C)
), so their associativity is inconsequential. "NA" (not
applicable) indicates that the EBNF does not allow an expression
that directly contains multiple operators from that precedence
level, so the question of their associativity does not arise.
Note:
Parentheses can be used to override the operator precedence in the usual way. Square brackets in an expression such as A[B] serve two roles: they act as an operator causing B to be evaluated once for each item in the value of A, and they act as parentheses enclosing the expression B.
[Definition: Under certain circumstances, an atomic value can be promoted from one type to another. Type promotion is used in evaluating function calls (see <IP_ADDRESS> Evaluating Static and Dynamic Function Calls ) and operators that accept numeric or string operands (see B.2 Operator Mapping).] The following type promotions are permitted:
Numeric type promotion:
A value of type xs:float
(or any type derived by
restriction from xs:float
) can be promoted to the type
xs:double
. The result is the xs:double
value that is the same as the original value.
A value of type xs:decimal
(or any type derived by
restriction from xs:decimal
) can be promoted to either
of the types xs:float
or xs:double
. The
result of this promotion is created by casting the original value
to the required type. This kind of promotion may cause loss of
precision.
URI type promotion: A value of type xs:anyURI
(or
any type derived by restriction from xs:anyURI
) can be
promoted to the type xs:string
. The result of this
promotion is created by casting the original value to the type
xs:string
.
Note:
Since xs:anyURI
values can be promoted to
xs:string
, functions and operators that compare
strings using the default collation also compare
xs:anyURI
values using the default collation.
This ensures that orderings that include strings,
xs:anyURI
values, or any combination of the two types
are consistent and well-defined.
Note that type promotion is different from subtype substitution. For example:
A function that expects a parameter $p
of type
xs:float
can be invoked with a value of type
xs:decimal
. This is an example of type promotion. The
value is actually converted to the expected type. Within the body
of the function, $p instance of xs:decimal
returns
false
.
A function that expects a parameter $p
of type
xs:decimal
can be invoked with a value of type
xs:integer
. This is an example of subtype
substitution. The value retains its original type. Within the
body of the function, $p instance of xs:integer
returns true
.
The operator mapping tables in this section list the combinations of types for which the various operators of XPath 3.0 are defined. [Definition: For each operator and valid combination of operand types, the operator mapping tables specify a result type and an operator function that implements the semantics of the operator for the given types.] The definitions of the operator functions are given in [XQuery and XPath Functions and Operators 3.0]. The result of an operator may be the raising of an error by its operator function, as defined in [XQuery and XPath Functions and Operators 3.0]. In some cases, the operator function does not implement the full semantics of a given operator. For the definition of each operator (including its behavior for empty sequences or sequences of length greater than one), see the descriptive material in the main part of this document.
The and
and or
operators are defined
directly in the main body of this document, and do not occur in the
operator mapping tables.
If an operator in the operator mapping tables expects an operand
of type ET, that operator can be applied to an operand of
type AT if type AT can be converted to type
ET by a combination of type promotion and subtype
substitution. For example, a table entry indicates that the
gt
operator may be applied to two xs:date
operands, returning xs:boolean
. Therefore, the
gt
operator may also be applied to two (possibly
different) subtypes of xs:date
, also returning
xs:boolean
.
[Definition: When referring to a type, the term
numeric denotes the types xs:integer
,
xs:decimal
, xs:float
, and
xs:double
.] An operator whose operands and result are
designated as numeric
might be thought of as representing four operators, one for each of
the numeric types. For example, the numeric +
operator
might be thought of as representing the following four
operators:
| Operator | First operand type | Second operand type | Result type |
+ |
xs:integer |
xs:integer |
xs:integer |
+ |
xs:decimal |
xs:decimal |
xs:decimal |
+ |
xs:float |
xs:float |
xs:float |
+ |
xs:double |
xs:double |
xs:double |
A numeric operator may be validly applied to an operand of type
AT if type AT can be converted to any of the four
numeric types by a combination of type promotion and subtype
substitution. If the result type of an operator is listed as
numeric, it means "the first type in the ordered list
(xs:integer, xs:decimal, xs:float, xs:double)
into
which all operands can be converted by subtype
substitution and type promotion." As an example, suppose
that the type hatsize
is derived from
xs:integer
and the type shoesize
is
derived from xs:float
. Then if the +
operator is invoked with operands of type hatsize
and
shoesize
, it returns a result of type
xs:float
. Similarly, if +
is invoked with
two operands of type hatsize
it returns a result of
type xs:integer
.
[Definition: In the operator mapping tables, the
term Gregorian refers to the types
xs:gYearMonth
, xs:gYear
,
xs:gMonthDay
, xs:gDay
, and
xs:gMonth
.] For binary operators that accept two
Gregorian-type operands, both operands must have the same type (for
example, if one operand is of type xs:gDay
, the other
operand must be of type xs:gDay
.)
| Operator | Type(A) | Type(B) | Function | Result type |
|---|---|---|---|---|
| A + B | numeric | numeric | op:numeric-add(A, B) | numeric |
| A + B | xs:date | xs:yearMonthDuration | op:add-yearMonthDuration-to-date(A, B) | xs:date |
| A + B | xs:yearMonthDuration | xs:date | op:add-yearMonthDuration-to-date(B, A) | xs:date |
| A + B | xs:date | xs:dayTimeDuration | op:add-dayTimeDuration-to-date(A, B) | xs:date |
| A + B | xs:dayTimeDuration | xs:date | op:add-dayTimeDuration-to-date(B, A) | xs:date |
| A + B | xs:time | xs:dayTimeDuration | op:add-dayTimeDuration-to-time(A, B) | xs:time |
| A + B | xs:dayTimeDuration | xs:time | op:add-dayTimeDuration-to-time(B, A) | xs:time |
| A + B | xs:dateTime | xs:yearMonthDuration | op:add-yearMonthDuration-to-dateTime(A, B) | xs:dateTime |
| A + B | xs:yearMonthDuration | xs:dateTime | op:add-yearMonthDuration-to-dateTime(B, A) | xs:dateTime |
| A + B | xs:dateTime | xs:dayTimeDuration | op:add-dayTimeDuration-to-dateTime(A, B) | xs:dateTime |
| A + B | xs:dayTimeDuration | xs:dateTime | op:add-dayTimeDuration-to-dateTime(B, A) | xs:dateTime |
| A + B | xs:yearMonthDuration | xs:yearMonthDuration | op:add-yearMonthDurations(A, B) | xs:yearMonthDuration |
| A + B | xs:dayTimeDuration | xs:dayTimeDuration | op:add-dayTimeDurations(A, B) | xs:dayTimeDuration |
| A - B | numeric | numeric | op:numeric-subtract(A, B) | numeric |
| A - B | xs:date | xs:date | op:subtract-dates(A, B) | xs:dayTimeDuration |
| A - B | xs:date | xs:yearMonthDuration | op:subtract-yearMonthDuration-from-date(A, B) | xs:date |
| A - B | xs:date | xs:dayTimeDuration | op:subtract-dayTimeDuration-from-date(A, B) | xs:date |
| A - B | xs:time | xs:time | op:subtract-times(A, B) | xs:dayTimeDuration |
| A - B | xs:time | xs:dayTimeDuration | op:subtract-dayTimeDuration-from-time(A, B) | xs:time |
| A - B | xs:dateTime | xs:dateTime | op:subtract-dateTimes(A, B) | xs:dayTimeDuration |
| A - B | xs:dateTime | xs:yearMonthDuration | op:subtract-yearMonthDuration-from-dateTime(A, B) | xs:dateTime |
| A - B | xs:dateTime | xs:dayTimeDuration | op:subtract-dayTimeDuration-from-dateTime(A, B) | xs:dateTime |
| A - B | xs:yearMonthDuration | xs:yearMonthDuration | op:subtract-yearMonthDurations(A, B) | xs:yearMonthDuration |
| A - B | xs:dayTimeDuration | xs:dayTimeDuration | op:subtract-dayTimeDurations(A, B) | xs:dayTimeDuration |
| A * B | numeric | numeric | op:numeric-multiply(A, B) | numeric |
| A * B | xs:yearMonthDuration | numeric | op:multiply-yearMonthDuration(A, B) | xs:yearMonthDuration |
| A * B | numeric | xs:yearMonthDuration | op:multiply-yearMonthDuration(B, A) | xs:yearMonthDuration |
| A * B | xs:dayTimeDuration | numeric | op:multiply-dayTimeDuration(A, B) | xs:dayTimeDuration |
| A * B | numeric | xs:dayTimeDuration | op:multiply-dayTimeDuration(B, A) | xs:dayTimeDuration |
| A idiv B | numeric | numeric | op:numeric-integer-divide(A, B) | xs:integer |
| A div B | numeric | numeric | op:numeric-divide(A, B) | numeric; but xs:decimal if both operands are xs:integer |
| A div B | xs:yearMonthDuration | numeric | op:divide-yearMonthDuration(A, B) | xs:yearMonthDuration |
| A div B | xs:dayTimeDuration | numeric | op:divide-dayTimeDuration(A, B) | xs:dayTimeDuration |
| A div B | xs:yearMonthDuration | xs:yearMonthDuration | op:divide-yearMonthDuration-by-yearMonthDuration (A, B) | xs:decimal |
| A div B | xs:dayTimeDuration | xs:dayTimeDuration | op:divide-dayTimeDuration-by-dayTimeDuration (A, B) | xs:decimal |
| A mod B | numeric | numeric | op:numeric-mod(A, B) | numeric |
| A eq B | numeric | numeric | op:numeric-equal(A, B) | xs:boolean |
| A eq B | xs:boolean | xs:boolean | op:boolean-equal(A, B) | xs:boolean |
| A eq B | xs:string | xs:string | op:numeric-equal(fn:compare(A, B), 0) | xs:boolean |
| A eq B | xs:date | xs:date | op:date-equal(A, B) | xs:boolean |
| A eq B | xs:time | xs:time | op:time-equal(A, B) | xs:boolean |
| A eq B | xs:dateTime | xs:dateTime | op:dateTime-equal(A, B) | xs:boolean |
| A eq B | xs:duration | xs:duration | op:duration-equal(A, B) | xs:boolean |
| A eq B | Gregorian | Gregorian | op:gYear-equal(A, B) etc. | xs:boolean |
| A eq B | xs:hexBinary | xs:hexBinary | op:hexBinary-equal(A, B) | xs:boolean |
| A eq B | xs:base64Binary | xs:base64Binary | op:base64Binary-equal(A, B) | xs:boolean |
| A eq B | xs:anyURI | xs:anyURI | op:numeric-equal(fn:compare(A, B), 0) | xs:boolean |
| A eq B | xs:QName | xs:QName | op:QName-equal(A, B) | xs:boolean |
| A eq B | xs:NOTATION | xs:NOTATION | op:NOTATION-equal(A, B) | xs:boolean |
| A ne B | numeric | numeric | fn:not(op:numeric-equal(A, B)) | xs:boolean |
| A ne B | xs:boolean | xs:boolean | fn:not(op:boolean-equal(A, B)) | xs:boolean |
| A ne B | xs:string | xs:string | fn:not(op:numeric-equal(fn:compare(A, B), 0)) | xs:boolean |
| A ne B | xs:date | xs:date | fn:not(op:date-equal(A, B)) | xs:boolean |
| A ne B | xs:time | xs:time | fn:not(op:time-equal(A, B)) | xs:boolean |
| A ne B | xs:dateTime | xs:dateTime | fn:not(op:dateTime-equal(A, B)) | xs:boolean |
| A ne B | xs:duration | xs:duration | fn:not(op:duration-equal(A, B)) | xs:boolean |
| A ne B | Gregorian | Gregorian | fn:not(op:gYear-equal(A, B)) etc. | xs:boolean |
| A ne B | xs:hexBinary | xs:hexBinary | fn:not(op:hexBinary-equal(A, B)) | xs:boolean |
| A ne B | xs:base64Binary | xs:base64Binary | fn:not(op:base64Binary-equal(A, B)) | xs:boolean |
| A ne B | xs:anyURI | xs:anyURI | fn:not(op:numeric-equal(fn:compare(A, B), 0)) | xs:boolean |
| A ne B | xs:QName | xs:QName | fn:not(op:QName-equal(A, B)) | xs:boolean |
| A ne B | xs:NOTATION | xs:NOTATION | fn:not(op:NOTATION-equal(A, B)) | xs:boolean |
| A gt B | numeric | numeric | op:numeric-greater-than(A, B) | xs:boolean |
| A gt B | xs:boolean | xs:boolean | op:boolean-greater-than(A, B) | xs:boolean |
| A gt B | xs:string | xs:string | op:numeric-greater-than(fn:compare(A, B), 0) | xs:boolean |
| A gt B | xs:date | xs:date | op:date-greater-than(A, B) | xs:boolean |
| A gt B | xs:time | xs:time | op:time-greater-than(A, B) | xs:boolean |
| A gt B | xs:dateTime | xs:dateTime | op:dateTime-greater-than(A, B) | xs:boolean |
| A gt B | xs:yearMonthDuration | xs:yearMonthDuration | op:yearMonthDuration-greater-than(A, B) | xs:boolean |
| A gt B | xs:dayTimeDuration | xs:dayTimeDuration | op:dayTimeDuration-greater-than(A, B) | xs:boolean |
| A gt B | xs:anyURI | xs:anyURI | op:numeric-greater-than(fn:compare(A, B), 0) | xs:boolean |
| A lt B | numeric | numeric | op:numeric-less-than(A, B) | xs:boolean |
| A lt B | xs:boolean | xs:boolean | op:boolean-less-than(A, B) | xs:boolean |
| A lt B | xs:string | xs:string | op:numeric-less-than(fn:compare(A, B), 0) | xs:boolean |
| A lt B | xs:date | xs:date | op:date-less-than(A, B) | xs:boolean |
| A lt B | xs:time | xs:time | op:time-less-than(A, B) | xs:boolean |
| A lt B | xs:dateTime | xs:dateTime | op:dateTime-less-than(A, B) | xs:boolean |
| A lt B | xs:yearMonthDuration | xs:yearMonthDuration | op:yearMonthDuration-less-than(A, B) | xs:boolean |
| A lt B | xs:dayTimeDuration | xs:dayTimeDuration | op:dayTimeDuration-less-than(A, B) | xs:boolean |
| A lt B | xs:anyURI | xs:anyURI | op:numeric-less-than(fn:compare(A, B), 0) | xs:boolean |
| A ge B | numeric | numeric | op:numeric-greater-than(A, B) or op:numeric-equal(A, B) | xs:boolean |
| A ge B | xs:boolean | xs:boolean | fn:not(op:boolean-less-than(A, B)) | xs:boolean |
| A ge B | xs:string | xs:string | op:numeric-greater-than(fn:compare(A, B), -1) | xs:boolean |
| A ge B | xs:date | xs:date | fn:not(op:date-less-than(A, B)) | xs:boolean |
| A ge B | xs:time | xs:time | fn:not(op:time-less-than(A, B)) | xs:boolean |
| A ge B | xs:dateTime | xs:dateTime | fn:not(op:dateTime-less-than(A, B)) | xs:boolean |
| A ge B | xs:yearMonthDuration | xs:yearMonthDuration | fn:not(op:yearMonthDuration-less-than(A, B)) | xs:boolean |
| A ge B | xs:dayTimeDuration | xs:dayTimeDuration | fn:not(op:dayTimeDuration-less-than(A, B)) | xs:boolean |
| A ge B | xs:anyURI | xs:anyURI | op:numeric-greater-than(fn:compare(A, B), -1) | xs:boolean |
| A le B | numeric | numeric | op:numeric-less-than(A, B) or op:numeric-equal(A, B) | xs:boolean |
| A le B | xs:boolean | xs:boolean | fn:not(op:boolean-greater-than(A, B)) | xs:boolean |
| A le B | xs:string | xs:string | op:numeric-less-than(fn:compare(A, B), 1) | xs:boolean |
| A le B | xs:date | xs:date | fn:not(op:date-greater-than(A, B)) | xs:boolean |
| A le B | xs:time | xs:time | fn:not(op:time-greater-than(A, B)) | xs:boolean |