using the expression fn:exists($N intersect $S)
may be expensive; there
may then be performance benefits in creating a map:
let $SMap := map:merge($S!map{fn:generate-id(.) : .})
and then testing for membership of the node-set using:
map:contains($SMap, fn:generate-id($N))
The functions in this section provide access to resources (such as files) in the external environment.
| Function | Meaning |
|---|---|
fn:doc |
Retrieves a document using a URI supplied as an xs:string , and returns the
corresponding document node.
|
fn:doc-available |
The function returns true if and only if the function call fn:doc($uri)
would return a document node.
|
fn:collection |
Returns a sequence of items identified by a collection URI; or a default collection if no URI is supplied. |
fn:uri-collection |
Returns a sequence of xs:anyURI values representing the URIs in a URI
collection.
|
fn:unparsed-text |
The fn:unparsed-text function reads an external resource (for example, a
file) and returns a string representation of the resource.
|
fn:unparsed-text-lines |
The fn:unparsed-text-lines function reads an external resource (for
example, a file) and returns its contents as a sequence of strings, one for each line
of
text in the string representation of the resource.
|
fn:unparsed-text-available |
Because errors in evaluating the fn:unparsed-text function are
non-recoverable, these two functions are provided to allow an application to determine
whether a call with particular arguments would succeed.
|
fn:environment-variable |
Returns the value of a system environment variable, if it exists. |
fn:available-environment-variables |
Returns a list of environment variable names that are suitable for passing to
fn:environment-variable , as a (possibly empty) sequence of strings.
|
Retrieves a document using a URI supplied as an xs:string
, and returns the
corresponding document node.
fn:doc
($uri
as
xs:string?
) as
document-node()?
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on available documents, and static base URI.
If $uri
is the empty sequence, the result is an empty sequence.
If $uri
is a relative URI reference, it is resolved relative to the value
of the static base URI property from the static context. The resulting absolute URI is
promoted to an xs:string
.
If the available documents described in Section 2.1.2 Dynamic Context XP31 provides a mapping from this string to a document node, the function returns that document node.
The URI may include a fragment identifier.
By default, this function is ·deterministic·. Two calls on this function return the same document node if the same URI Reference (after resolution to an absolute URI Reference) is supplied to both calls. Thus, the following expression (if it does not raise an error) will always be true:
doc("foo.xml") is doc("foo.xml")
However, for performance reasons, implementations may provide a user option to evaluate the function without a guarantee of determinism. The manner in which any such option is provided is implementation-defined. If the user has not selected such an option, a call of the function must either return a deterministic result or must raise a dynamic error [err:FODC0003].
Note:
If $uri
is read from a source document, it is generally appropriate to
resolve it relative to the base URI property of the relevant node in the source
document. This can be achieved by calling the fn:resolve-uri
function,
and passing the resulting absolute URI as an argument to the fn:doc
function.
If two calls to this function supply different absolute URI References as arguments, the same document node may be returned if the implementation can determine that the two arguments refer to the same resource.
By defining the semantics of this function in terms of a string-to-document-node mapping in the dynamic context, the specification is acknowledging that the results of this function are outside the purview of the language specification itself, and depend entirely on the run-time environment in which the expression is evaluated. This run-time environment includes not only an unpredictable collection of resources ("the web"), but configurable machinery for locating resources and turning their contents into document nodes within the XPath data model. Both the set of resources that are reachable, and the mechanisms by which those resources are parsed and validated, are ·implementation-dependent·.
One possible processing model for this function is as follows. The resource identified by the URI Reference is retrieved. If the resource cannot be retrieved, a dynamic error is raised [err:FODC0002]. The data resulting from the retrieval action is then parsed as an XML document and a tree is constructed in accordance with the [XQuery and XPath Data Model (XDM) 3.0]. If the top-level media type is known and is "text", the content is parsed in the same way as if the media type were text/xml; otherwise, it is parsed in the same way as if the media type were application/xml. If the contents cannot be parsed successfully, a dynamic error is raised [err:FODC0002]. Otherwise, the result of the function is the document node at the root of the resulting tree. This tree is then optionally validated against a schema.
Various aspects of this processing are ·implementation-defined·. Implementations may provide external configuration options that allow any aspect of the processing to be controlled by the user. In particular:
The set of URI schemes that the implementation recognizes is implementation-defined. Implementations may allow the mapping of URIs to resources to be configured by the user, using mechanisms such as catalogs or user-written URI handlers.
The handling of non-XML media types is implementation-defined. Implementations may allow instances of the data model to be constructed from non-XML resources, under user control.
It is ·implementation-defined· whether DTD validation and/or schema validation is applied to the source document.
Implementations may provide user-defined error handling options that allow processing to continue following an error in retrieving a resource, or in parsing and validating its content. When errors have been handled in this way, the function may return either an empty sequence, or a fallback document provided by the error handler.
Implementations may provide user options that relax the requirement for the function to return deterministic results.
The effect of a fragment identifier in the supplied URI is ·implementation-defined·. One possible interpretation is to treat the fragment identifier as an ID attribute value, and to return a document node having the element with the selected ID value as its only child.
A dynamic error may be raised [err:FODC0005] if
$uri
is not a valid URI reference.
A dynamic error is raised [err:FODC0002] if a relative URI reference is supplied, and the base-URI property in the static context is absent.
A dynamic error is raised [err:FODC0002] if the available documents provides no mapping for the absolutized URI.
A dynamic error is raised [err:FODC0002] if the resource cannot be retrieved or cannot be parsed successfully as XML.
A dynamic error is raised [err:FODC0003] if the implementation is not able to guarantee that the result of the function will be deterministic, and the user has not indicated that an unstable result is acceptable.
The function returns true if and only if the function call fn:doc($uri)
would return a document node.
fn:doc-available
($uri
as
xs:string?
) as
xs:boolean
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on available documents, and static base URI.
If $uri
is an empty sequence, this function returns false
.
If a call on fn:doc($uri)
would return a document node, this function
returns true
.
In all other cases this function returns false
. This
includes the case where an invalid URI is supplied, and also the case where
a valid relative URI reference is supplied, and cannot be resolved,
for example because the static base URI is absent.
If this function returns true
, then calling fn:doc($uri)
within the same ·execution scope· must return a document node. However,
if nondeterministic processing has been selected for the fn:doc
function,
this guarantee is lost.
Returns a sequence of items identified by a collection URI; or a default collection if no URI is supplied.
fn:collection
() as
item()*
fn:collection
($arg
as
xs:string?
) as
item()*
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on available collections, and static base URI.
This function takes an xs:string
as argument and returns a sequence of
items obtained by interpreting $arg
as an xs:anyURI
and
resolving it according to the mapping specified in available
collections described in Section
C.2 Dynamic Context Components
XP31.
If available collections provides a mapping from this string to a sequence of items, the function returns that sequence. If available collections maps the string to an empty sequence, then the function returns an empty sequence.
If $arg
is not specified, the function returns the sequence of items in
the default collection in the dynamic context. See Section
C.2 Dynamic Context Components
XP31.
If the value of $arg
is a relative xs:anyURI
, it is resolved
against the value of the base-URI property from the static context.
If $arg
is the empty sequence, the function behaves as if it had been
called without an argument. See above.
By default, this function is ·deterministic·. This means that repeated calls on the function with the same argument will return the same result. However, for performance reasons, implementations may provide a user option to evaluate the function without a guarantee of determinism. The manner in which any such option is provided is ·implementation-defined·. If the user has not selected such an option, a call to this function must either return a deterministic result or must raise a dynamic error [err:FODC0003].
There is no requirement that any nodes in the result should be in document order, nor is there a requirement that the result should contain no duplicates.
A dynamic error is raised [err:FODC0002] if no URI is supplied and the value of the default collection is absentDM31.
A dynamic error is raised [err:FODC0002] if a relative URI reference is supplied, and the base-URI property in the static context is absent.
A dynamic error is raised [err:FODC0002] if available node collections provides no mapping for the absolutized URI.
A dynamic error may be raised [err:FODC0004] if $arg
is not
a valid xs:anyURI
.
In earlier releases, the primary use for the fn:collection
function
was to retrieve a collection of XML documents, perhaps held as lexical XML in operating
system filestore, or perhaps held in an XML database. In this release the concept
has
been generalised to allow other resources to be retrieved: for example JSON documents
might
be returned as arrays or maps, non-XML text files might be returned as strings, and
binary
files might be returned as instances of xs:base64Binary
.
The abstract concept of a collection might be realized in different ways by different implementations, and the ways in which URIs map to collections can be equally variable. Specifying resources using URIs is useful because URIs are dynamic, can be parameterized, and do not rely on an external environment.
Returns a sequence of xs:anyURI
values representing the URIs in a URI
collection.
fn:uri-collection
() as
xs:anyURI*
fn:uri-collection
($arg
as
xs:string?
) as
xs:anyURI*
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on available URI collections, and static base URI.
The zero-argument form of the function returns the URIs in the default URI collection described in Section C.2 Dynamic Context Components XP31.
If the value of $arg
is a relative xs:anyURI
, it is resolved
against the value of the base-URI property from the static context.
If $arg
is the empty sequence, the function behaves as if it had been
called without an argument. See above.
The single-argument form of the function returns the sequence of URIs corresponding to the supplied URI in the available URI collections described in Section C.2 Dynamic Context Components XP31.
By default, this function is ·deterministic·. This means that repeated calls on the function with the same argument will return the same result. However, for performance reasons, implementations may provide a user option to evaluate the function without a guarantee of determinism. The manner in which any such option is provided is ·implementation-defined·. If the user has not selected such an option, a call to this function must either return a deterministic result or must raise a dynamic error [err:FODC0003].
There is no requirement that the URIs returned by this function should all be distinct, and no assumptions can be made about the order of URIs in the sequence, unless the implementation defines otherwise.
A dynamic error is raised [err:FODC0002] if no URI is supplied (that is, if the function is called with no arguments, or with a single argument that evaluates to an empty sequence), and the value of the default resource collection is absentDM31.
A dynamic error is raised [err:FODC0002] if a relative URI reference is supplied, and the base-URI property in the static context is absent.
A dynamic error is raised [err:FODC0002] if available resource collections provides no mapping for the absolutized URI.
A dynamic error may be raised [err:FODC0004] if $arg
is not
a valid xs:anyURI
.
In some implementations, there might be a close relationship between collections (as retrieved
by the fn:collection
function), and URI collections (as retrieved by this function).
For example, a collection might return XML documents, and the corresponding URI collection
might return
the URIs of those documents. However, this specification does not impose such a close
relationship. For example, there
may be collection URIs accepted by one of the two functions and not by the other;
a collection might contain
items that do not have any URI; or a URI collection might contain URIs that cannot
be dereferenced to return any
resource.
Thus, some implementations might ensure that calling fn:uri-collection
and then
applying fn:doc
to each of the returned URIs delivers the same result as
calling fn:collection
with the same argument; however, this is not
guaranteed.
In the case where fn:uri-collection
returns the URIs of resources that
could also be retrieved directly using fn:collection
, there are several reasons why it
might be appropriate to use this function in preference
to the fn:collection
function. For example:
It allows different URIs for different kinds of resource to be dereferenced in
different ways: for
example, the returned URIs might be referenced using the
fn:unparsed-text
function rather than the fn:doc
function.
In XSLT 3.0 it allows the documents in a collection to be processed in streaming mode
using the
xsl:stream
instruction.
It allows recovery from failures to read, parse, or validate individual documents,
by calling the fn:doc
(or other dereferencing) function within the scope of try/catch.
It allows selection of which documents to read based on their URI, for example
they can be filtered to select those whose URIs end in .xml
, or those
that use the https
scheme.
An application might choose to limit the number of URIs processed in a single run, for example it might process only the first 50 URIs in the collection; or it might present the URIs to the user and allow the user to select which of them need to be further processed.
It allows the URIs to be modified before they are dereferenced, for example by adding or removing query parameters, or by redirecting the request to a local cache or to a mirror site.
For some of these use cases, this assumes that the cost of calling
fn:collection
might be significant (for example, it might involving
retrieving all the documents in the collection over the network and parsing them).
This
will not necessarily be true of all implementations.
The fn:unparsed-text
function reads an external resource (for example, a
file) and returns a string representation of the resource.
fn:unparsed-text
($href
as
xs:string?
) as
xs:string?
fn:unparsed-text
($href
as
xs:string?
, $encoding
as
xs:string
) as
xs:string?
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.
The $href
argument must be a string in the form of a URI
reference, which must contain no fragment identifier, and
must identify a resource for which a string representation is
available. If the URI is a relative URI reference, then it is resolved relative to
the
static base URI property from the static context.
The mapping of URIs to the string representation of a resource is the mapping defined in the available text resourcesXP31 component of the dynamic context.
If the value of the $href
argument is an empty sequence, the function
returns an empty sequence.
The $encoding
argument, if present, is the name of an encoding. The values
for this attribute follow the same rules as for the encoding
attribute in
an XML declaration. The only values which every ·implementation· is required to recognize are
utf-8
and utf-16
.
The encoding of the external resource is determined as follows:
external encoding information is used if available, otherwise
if the media type of the resource is text/xml
or
application/xml
(see [RFC 2376]), or if it matches
the conventions text/*+xml
or application/*+xml
(see
[RFC 7303] and/or its successors), then the encoding is recognized
as specified in [Extensible Markup Language (XML) 1.0 (Fifth Edition)], otherwise
the value of the $encoding
argument is used if present, otherwise
the processor may use ·implementation-defined· heuristics to determine the likely encoding, otherwise
UTF-8 is assumed.
The result of the function is a string containing the string representation of the resource retrieved using the URI.
A dynamic error is raised [err:FOUT1170] if $href
contains a fragment identifier, or if it cannot be resolved
to an absolute URI (for example, because the base-URI property in the static context
is absent),
or if it cannot be used to retrieve the string
representation of a resource.
A dynamic error is raised [err:FOUT1190] if the value of the
$encoding
argument is not a valid encoding name, if the ·processor· does not support the specified encoding, if
the string representation of the retrieved resource contains octets that cannot be
decoded into Unicode ·characters· using the specified
encoding, or if the resulting characters are not permitted XML characters.
A dynamic error is raised [err:FOUT1200] if $encoding
is absent and the ·processor· cannot infer the
encoding using external information and the encoding is not UTF-8.
If it is appropriate to use a base URI other than the dynamic base URI (for example,
when resolving a relative URI reference read from a source document) then it is
advisable to resolve the relative URI reference using the fn:resolve-uri
function before passing it to the fn:unparsed-text
function.
There is no essential relationship between the sets of URIs accepted by the two
functions fn:unparsed-text
and fn:doc
(a URI accepted by one
may or may not be accepted by the other), and if a URI is accepted by both there is
no
essential relationship between the results (different resource representations are
permitted by the architecture of the web).
There are no constraints on the MIME type of the resource.
The fact that the resolution of URIs is defined by a mapping in the dynamic context means that in effect, various aspects of the behavior of this function are ·implementation-defined·. Implementations may provide external configuration options that allow any aspect of the processing to be controlled by the user. In particular:
The set of URI schemes that the implementation recognizes is implementation-defined. Implementations may allow the mapping of URIs to resources to be configured by the user, using mechanisms such as catalogs or user-written URI handlers.
The handling of media types is implementation-defined.
Implementations may provide user-defined error handling options that allow processing to continue following an error in retrieving a resource, or in reading its content. When errors have been handled in this way, the function may return a fallback document provided by the error handler.
Implementations may provide user options that relax the requirement for the function to return deterministic results.
The rules for determining the encoding are chosen for consistency with [XML Inclusions (XInclude) Version 1.0 (Second Edition)]. Files with an XML media type are treated specially because there are use cases for this function where the retrieved text is to be included as unparsed XML within a CDATA section of a containing document, and because processors are likely to be able to reuse the code that performs encoding detection for XML external entities.
If the text file contains characters such as <
and &
,
these will typically be output as <
and &
if
the string is serialized as XML or HTML. If these characters actually represent markup
(for example, if the text file contains HTML), then an XSLT stylesheet can attempt
to
write them as markup to the output file using the disable-output-escaping
attribute of the xsl:value-of
instruction. Note, however, that XSLT
implementations are not required to support this feature.
This XSLT example attempts to read a file containing 'boilerplate' HTML and copy it directly to the serialized output file:
<xsl:output method="html"/> <xsl:template match="/"> <xsl:value-of select="unparsed-text('header.html', 'iso-8859-1')" disable-output-escaping="yes"/> <xsl:apply-templates/> <xsl:value-of select="unparsed-text('footer.html', 'iso-8859-1')" disable-output-escaping="yes"/> </xsl:template>
The fn:unparsed-text-lines
function reads an external resource (for
example, a file) and returns its contents as a sequence of strings, one for each line
of
text in the string representation of the resource.
fn:unparsed-text-lines
($href
as
xs:string?
) as
xs:string*
fn:unparsed-text-lines (
|
$href |
as xs:string? ,
|
$encoding |
as xs:string ) as xs:string* |
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.
The unparsed-text-lines
function reads an external resource (for example, a
file) and returns its string representation as a sequence of strings, separated at
newline boundaries.
The result of the single-argument function is the same as the result of the expression
fn:tokenize(fn:unparsed-text($href), '\r\n|\r|\n')[not(position()=last() and
.='')]
. The result of the two-argument function is the same as the result of
the expression fn:tokenize(fn:unparsed-text($href, $encoding),
'\r\n|\r|\n')[not(position()=last() and .='')]
.
The result is thus a sequence of strings containing the text of the resource retrieved using the URI, each string representing one line of text. Lines are separated by one of the sequences x0A, x0D, or x0Dx0A. The characters representing the newline are not included in the returned strings. If there are two adjacent newline sequences, a zero-length string will be returned to represent the empty line; but if the external resource ends with the sequence x0A, x0D, or x0Dx0A, the result will be as if this final line ending were not present.
Error conditions are the same as for the fn:unparsed-text
function.
See the notes for fn:unparsed-text
.
Because errors in evaluating the fn:unparsed-text
function are
non-recoverable, these two functions are provided to allow an application to determine
whether a call with particular arguments would succeed.
fn:unparsed-text-available
($href
as
xs:string?
) as
xs:boolean
fn:unparsed-text-available (
|
$href |
as xs:string? ,
|
$encoding |
as xs:string ) as xs:boolean |
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.
The fn:unparsed-text-available
function determines whether a call
on the fn:unparsed-text
function with identical arguments would
return a string.
If the first argument is an empty sequence, the function returns false.
In other cases, the function returns true if a call on
fn:unparsed-text
with the same arguments would succeed, and
false if a call on fn:unparsed-text
with the same arguments would
fail with a non-recoverable dynamic error.
The functions fn:unparsed-text
and
fn:unparsed-text-available
have the same requirement for
·determinism· as the functions
fn:doc
and fn:doc-available
. This means that unless the
user has explicitly stated a requirement for a reduced level of determinism, either
of
these functions if called twice with the same arguments during the course of a
transformation must return the same results each time; moreover, the
results of a call on fn:unparsed-text-available
must be consistent with the results of a subsequent call on
unparsed-text
with the same arguments.
This requires that the fn:unparsed-text-available
function should
actually attempt to read the resource identified by the URI, and check that it is
correctly encoded and contains no characters that are invalid in XML. Implementations
may avoid the cost of repeating these checks for example by caching the validated
contents of the resource, to anticipate a subsequent call on the
fn:unparsed-text
or fn:unparsed-text-lines
function. Alternatively, implementations may be able to rewrite an expression such
as
if (unparsed-text-available(A)) then unparsed-text(A) else ...
to
generate a single call internally.
Since the function fn:unparsed-text-lines
succeeds or fails under
exactly the same circumstances as fn:unparsed-text
, the
fn:unparsed-text-available
function may equally be used to test
whether a call on fn:unparsed-text-lines
would succeed.
Returns the value of a system environment variable, if it exists.
fn:environment-variable
($name
as
xs:string
) as
xs:string?
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on environment variables.
The set of available environment variablesXP31 is a set of (name, value) pairs forming part of the dynamic context, in which the name is unique within the set of pairs. The name and value are arbitrary strings.
If the $name
argument matches the name of one of these pairs, the function
returns the corresponding value.
If there is no environment variable with a matching name, the function returns the empty sequence.
The collation used for matching names is ·implementation-defined·, but must be the same as the collation used to ensure that the names of all environment variables are unique.
The function is ·deterministic·, which means that if it is called several times within the same ·execution scope·, with the same arguments, it must return the same result.
On many platforms, the term "environment variable" has a natural meaning in terms of facilities provided by the operating system. This interpretation of the concept does not exclude other interpretations, such as a mapping to a set of configuration parameters in a database system.
Environment variable names are usually case sensitive. Names are usually of the form
(letter|_) (letter|_|digit)*
, but this varies by platform.
On some platforms, there may sometimes be multiple environment variables with the same name; in this case, it is implementation-dependent as to which is returned; see for example [POSIX.1-2008] (Chapter 8, Environment Variables). Implementations may use prefixes or other naming conventions to disambiguate the names.
The requirement to ensure that the function is deterministic means in practice that the implementation must make a snapshot of the environment variables at some time during execution, and return values obtained from this snapshot, rather than using live values that are subject to change at any time.
Operating system environment variables may be associated with a particular process, while queries and stylesheets may execute across multiple processes (or multiple machines). In such circumstances implementations may choose to provide access to the environment variables associated with the process in which the query or stylesheet processing was initiated.
Security advice: Queries from untrusted sources should not be permitted unrestricted
access to environment variables. For example, the name of the account under which
the
query is running may be useful information to a would-be intruder. An implementation
may
therefore choose to restrict access to the environment, or may provide a facility
to
make fn:environment-variable
always return the empty sequence.
Returns a list of environment variable names that are suitable for passing to
fn:environment-variable
, as a (possibly empty) sequence of strings.
fn:available-environment-variables
() as
xs:string*
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on environment variables.
The function returns a sequence of strings, being the names of the environment variables in the dynamic context in some ·implementation-dependent· order.
The function is ·deterministic·: that is, the set of available environment variables does not vary during evaluation.
The function returns a list of strings, containing no duplicates.
It is intended that the strings in this list should be suitable for passing to
fn:environment-variable
.
See also the note on security under the definition of the
fn:environment-variable
function. If access to environment variables has
been disabled, fn:available-environment-variables
always returns the empty
sequence.
These functions convert between the lexical representation of XML and the tree representation.
| Function | Meaning |
|---|---|
fn:parse-xml |
This function takes as input an XML document represented as a string, and returns the document node at the root of an XDM tree representing the parsed document. |
fn:parse-xml-fragment |
This function takes as input an XML external entity represented as a string, and returns the document node at the root of an XDM tree representing the parsed document fragment. |
fn:serialize |
This function serializes the supplied input sequence $arg as described in
[XSLT and XQuery Serialization 3.1], returning the serialized representation
of the sequence as a string.
|
This function takes as input an XML document represented as a string, and returns the document node at the root of an XDM tree representing the parsed document.
fn:parse-xml
($arg
as
xs:string?
) as
document-node(element(*))?
This function is ·nondeterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.
If $arg
is the empty sequence, the function returns the empty sequence.
The precise process used to construct the XDM instance is ·implementation-defined·. In particular, it is implementation-defined whether DTD and/or schema validation is invoked, and it is implementation-defined whether an XML 1.0 or XML 1.1 parser is used.
The static base URI property from the static context of the fn:parse-xml
function call is used both as the base URI used by the XML parser to resolve relative
entity references within the document, and as the base URI of the document node that
is
returned.
The document URI of the returned node is ·absent·.
The function is not ·deterministic·: that is, if the function is called twice with the same arguments, it is ·implementation-dependent· whether the same node is returned on both occasions.
A dynamic error is raised [err:FODC0006] if the content of
$arg
is not a well-formed and namespace-well-formed XML document.
A dynamic error is raised [err:FODC0006] if DTD-based validation is
carried out and the content of $arg
is not valid against its DTD.
Since the XML document is presented to the parser as a string, rather than as a sequence of octets, the encoding specified within the XML declaration has no meaning. If the XML parser accepts input only in the form of a sequence of octets, then the processor must ensure that the string is encoded as octets in a way that is consistent with rules used by the XML parser to detect the encoding.
The primary use case for this function is to handle input documents that contain nested
XML documents embedded within CDATA sections. Since the content of the CDATA section
are
exposed as text, the receiving query or stylesheet may pass this text to the
fn:parse-xml
function to create a tree representation of the nested
document.
Similarly, nested XML within comments is sometimes encountered, and lexical XML is sometimes returned by extension functions, for example, functions that access web services or read from databases.
A use case arises in XSLT where there is a need to preprocess an input document before
parsing. For example, an application might wish to edit the document to remove its
DOCTYPE declaration. This can be done by reading the raw text using the
fn:unparsed-text
function, editing the resulting string, and then
passing it to the fn:parse-xml
function.
The expression fn:parse-xml("<alpha>abcd</alpha>")
returns a newly
created document node, having an alpha
element as its only child; the
alpha
element in turn is the parent of a text node whose string value
is "abcd"
.
This function takes as input an XML external entity represented as a string, and returns the document node at the root of an XDM tree representing the parsed document fragment.
fn:parse-xml-fragment
($arg
as
xs:string?
) as
document-node()?
This function is ·nondeterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.
If $arg
is the empty sequence, the function returns the empty sequence.
The input must be a namespace-well-formed external general parsed entity. More specifically, it must be a string conforming to the production rule extParsedEntxml in [Extensible Markup Language (XML) 1.0 (Fifth Edition)], it must contain no entity references other than references to predefined entities, and it must satisfy all the rules of [Namespaces in XML] for namespace-well-formed documents with the exception that the rule requiring it to be a well-formed document is replaced by the rule requiring it to be a well-formed external general parsed entity.
The string is parsed to form a sequence of nodes which become children of the new document node, in the same way as the content of any element is converted into a sequence of children for the resulting element node.
Schema validation is not invoked, which means that the nodes in the returned document will all be untyped.
The precise process used to construct the XDM instance is ·implementation-defined·. In particular, it is implementation-defined whether an XML 1.0 or XML 1.1 parser is used.
The static base URI from the static context of the fn:parse-xml-fragment
function call is used as the base URI of the document node that is returned.
The document URI of the returned node is ·absent·.
The function is not ·deterministic·: that is, if the function is called twice with the same arguments, it is ·implementation-dependent· whether the same node is returned on both occasions.
A dynamic error is raised [err:FODC0006] if the content of
$arg
is not a well-formed external general parsed entity, if it contains
entity references other than references to predefined entities, or if a document that
incorporates this well-formed parsed entity would not be namespace-well-formed.
See also the notes for the fn:parse-xml
function.
The main differences between fn:parse-xml
and
fn:parse-xml-fragment
are that for fn:parse-xml
, the
children of the resulting document node must contain exactly one element node and
no
text nodes, wheras for fn:parse-xml-fragment
, the resulting document node
can have any number (including zero) of element and text nodes among its children.
An
additional difference is that the text declaration at the start of an
external entity has slightly different syntax from the XML declaration at
the start of a well-formed document.
Note that all whitespace outside the text declaration is significant, including whitespace that precedes the first element node.
One use case for this function is to handle XML fragments stored in databases, which
frequently allow zero-or-more top level element nodes. Another use case is to parse
the
contents of a CDATA
section embedded within another XML document.
The expression
fn:parse-xml-fragment("<alpha>abcd</alpha><beta>abcd</beta>")
returns a newly created document node, having two elements named alpha
and beta
as its children; each of these elements in turn is the parent
of a text node.
The expression fn:parse-xml-fragment("He was <i>so</i> kind")
returns a newly created document node having three children: a text node whose string
value is "He was "
, an element node named i
having a child
text node with string value "so"
, and a text node whose string value is
" kind"
.
The expression fn:parse-xml-fragment("")
returns a document node having
no children.
The expression fn:parse-xml-fragment(" ")
returns a document node whose
children comprise a single text node whose string value is a single space.
The expression fn:parse-xml-fragment('<xml version="1.0" encoding="utf8"
standalone="yes"?></a>")
results in a dynamic error [err:FODC0006] because the "standalone" keyword is not permitted in the text
declaration that appears at the start of an external general parsed entity. (Thus,
it
is not the case that any input accepted by the fn:parse-xml
function
will also be accepted by fn:parse-xml-fragment
.)
This function serializes the supplied input sequence $arg
as described in
[XSLT and XQuery Serialization 3.1], returning the serialized representation
of the sequence as a string.
fn:serialize
($arg
as
item()*
) as
xs:string
fn:serialize
($arg
as
item()*
, $params
as
item()?
) as
xs:string
This function is ·deterministic·, ·context-independent·, and ·focus-independent·.
The value of the first argument $arg
acts as the input sequence to the serialization process,
which starts with sequence normalization.
The second argument $params
, if present, provides serialization parameters. These may be supplied in either
of two forms:
As an output:serialization-parameters
element, having the format described in Section
3.1 Setting Serialization Parameters by Means of a Data Model Instance
SER31. In this case the type of the supplied
argument must match the required type element(output:serialization-parameters)
.
As a map. In this case the type of the supplied argument must match the required type
map(*)
The single-argument version of this function has the same effect as the two-argument
version called with $params
set to an empty sequence. This in turn is the
same as the effect of passing an output:serialization-parameters
element
with no child elements.
The final stage of serialization, that is, encoding, is skipped. If the serializer does not allow this phase to be skipped, then the sequence of octets returned by the serializer is decoded into a string by reversing the character encoding performed in the final stage.
If the second argument is omitted, or is supplied in the form of an output:serialization-parameters
element, then the values of any serialization parameters that are not explicitly specified
is ·implementation-defined·,
and may depend on the context.
If the second argument is supplied as a map, then the ·option parameter conventions· apply. In this case:
Each entry in the map defines one serialization parameter.
The key of the entry is an xs:string
value in the cases of parameter names defined in these specifications, or an
xs:QName
(with non-absent namespace) in the case of implementation-defined serialization parameters.
The required type of each parameter, and its default value, are defined by the following table. The default value is used when the map contains no entry for the parameter in question, and also when an entry is present, with the empty sequence as its value. The table also indicates how the value of the map entry is to be interpreted in cases where further explanation is needed.
| Parameter | Required type | Interpretation | Default Value |
|---|---|---|---|
allow-duplicate-names |
xs:boolean? |
true() means "yes", false() means "no"
|
no |
byte-order-mark |
xs:boolean? |
true() means "yes", false() means "no"
|
no |
cdata-section-elements |
xs:QName* |
() |
|
doctype-public |
xs:string? |
Zero-length string and () both represent "absent"
|
absent |
doctype-system |
xs:string? |
Zero-length string and () both represent "absent"
|
absent |
encoding |
xs:string? |
utf-8 |
|
escape-uri-attributes |
xs:boolean? |
true() means "yes", false() means "no"
|
yes |
html-version |
xs:decimal? |
5 |
|
include-content-type |
xs:boolean? |
true() means "yes", false() means "no"
|
yes |
indent |
xs:boolean? |
true() means "yes", false() means "no"
|
no |
item-separator |
xs:string? |
absent | |
json-node-output-method |
union(xs:string, xs:QName)? |
See Notes 1, 2 | xml |
media-type |
xs:string? |
(a media type suitable for the chosen method )
|
|
method |
union(xs:string, xs:QName)? |
See Notes 1, 2 | xml |
normalization-form |
xs:string? |
none |
|
omit-xml-declaration |
xs:boolean? |
true() means "yes", false() means "no"
|
yes |
standalone |
xs:boolean? |
true() means "yes", false() means "no", () means "omit"
|
omit |
suppress-indentation |
xs:QName* |
() |
|
undeclare-prefixes |
xs:boolean? |
true() means "yes", false() means "no"
|
no |
use-character-maps |
map(xs:string, xs:string)? |
See Note 3 | map{} |
version |
xs:string? |
1.0 |
Notes to the table:
The notation union(A, B)
is used to represent a union type whose member types are A
and B
.
If an xs:QName
is supplied for the method
or json-node-output-method
options, then it must have a non-absent namespace URI. This
means that system-defined serialization methods such as xml
and json
are defined as strings, not as xs:QName
values.
For the use-character-maps
option, the value is a map, whose keys
are the characters to be mapped (as xs:string
instances),
and whose corresponding values are the strings to be substituted for these characters.
A type error [err:XPTY0004]XP31 occurs if the second argument
is present and does not match either of the types element(output:serialization-parameters)?
or map(*)
.
Note:
This is defined as a type error so that it can be enforced via the function signature by implementations that generalize the type system in a suitable way.
If the host language makes serialization an optional feature and the implementation does not support serialization, then a dynamic error [err:FODC0010] is raised.
The serialization process will raise an error if $arg
is an attribute or
namespace node.
When the second argument is supplied as a map,
and the supplied value is of the wrong type for the particular parameter, for example
if the value of indent
is a string rather than a boolean, then as defined by the ·option parameter conventions·,
a type error [err:XPTY0004]XP31 is raised.
If the value is of the correct type, but does not satisfy the rules for that
parameter defined in [XSLT and XQuery Serialization 3.1], then a dynamic error
[err:SEPM0016]SER31 is raised. (For example, this occurs if the map supplied to
use-character-maps
includes a key that is a string whose length is not one (1)).
If any serialization error occurs, including the detection of an invalid value for
a
serialization parameter as described above, this results in the fn:serialize
call failing with
a dynamic error.
One use case for this function arises when there is a need to construct an XML document
containing nested XML documents within a CDATA section (or on occasions within a
comment). See fn:parse-xml
for further details.
Another use case arises when there is a need to call an extension function that expects a lexical XML document as input.
There are also use cases where the application wants to post-process the output of
a
query or transformation, for example by adding an internal DTD subset, or by inserting
proprietary markup delimiters such as the <% ... %>
used by some
templating languages.
The ability to specify the serialization parameters in an output:serialization-parameters
element provides backwards compatibility with the 3.0 version of this specification;
the ability to
use a map takes advantage of new features in the 3.1 version. The default parameter
values are
implementation-defined when an output:serialization-parameters
element is used (or when the argument is omitted), but are fixed by this specification
in the
case where a map (including an empty map) is supplied for the argument.
Given the variables:
let $params := <output:serialization-parameters xmlns:output="http://www.w3.org/2010/xslt-xquery-serialization"> <output:omit-xml-declaration value="yes"/> </output:serialization-parameters>
let $data := <a b="3"/>
The following call might produce the output shown:
The expression fn:serialize($data, $params)
returns '<a b="3"/>'
.
The following call would also produce the output shown (though the second argument
could equally well be supplied
as an empty map (map{}
), since both parameters are given their default values):
The expression fn:serialize($data, map{"method":"xml", "omit-xml-declaration":true()})
returns '<a b="3"/>'
.
The following functions are defined to obtain information from the static or dynamic context.
| Function | Meaning |
|---|---|
fn:position |
Returns the context position from the dynamic context. |
fn:last |
Returns the context size from the dynamic context. |
fn:current-dateTime |
Returns the current date and time (with timezone). |
fn:current-date |
Returns the current date. |
fn:current-time |
Returns the current time. |
fn:implicit-timezone |
Returns the value of the implicit timezone property from the dynamic context. |
fn:default-collation |
Returns the value of the default collation property from the static context. |
fn:default-language |
Returns the value of the default language property from the dynamic context. |
fn:static-base-uri |
This function returns the value of the static base URI property from the static context. |
Returns the context position from the dynamic context.
fn:position
() as
xs:integer
This function is ·deterministic·, ·context-dependent·, and ·focus-dependent·.
Returns the context position from the dynamic context. (See Section C.2 Dynamic Context Components XP31.)
A dynamic error is raised [err:XPDY0002]XP31 if the context item is absentDM31.
Returns the context size from the dynamic context.
fn:last
() as
xs:integer
This function is ·deterministic·, ·context-dependent·, and ·focus-dependent·.
Returns the context size from the dynamic context. (See Section C.2 Dynamic Context Components XP31.)
A dynamic error is raised [err:XPDY0002]XP31 if the context size is absentDM31.
Under most circumstances, the context size is absent only if the context item is absent. However, XSLT 3.0 with streaming defines situations in which the context item and context position are known, but the context size is unknown.
The expression (1 to 20)[fn:last() - 1]
returns 19
.
Returns the current date and time (with timezone).
fn:current-dateTime
() as
xs:dateTimeStamp
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on implicit timezone.
Returns the current dateTime (with timezone) from the dynamic context. (See Section
C.2 Dynamic Context Components
XP31.) This is an
xs:dateTime
that is current at some time during the evaluation of a
query or transformation in which fn:current-dateTime
is executed.
This function is ·deterministic·. The precise instant during the query
or transformation represented by the value of fn:current-dateTime()
is
·implementation-dependent·.
If the implementation supports data types from XSD 1.1 then the returned value will
be
an instance of xs:dateTimeStamp
. Otherwise, the only guarantees are that it
will be an instance of xs:dateTime
and will have a timezone component.
The returned xs:dateTime
will always have an associated timezone, which
will always be the same as the implicit timezone in the dynamic context
fn:current-dateTime()
returns an xs:dateTimeStamp
corresponding to the current date and time. For example, a call of
fn:current-dateTime()
might return
2004-05-12T18:17:15.125Z
corresponding to the current time on May 12,
2004 in timezone Z
.
Returns the current date.
fn:current-date
() as
xs:date
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on implicit timezone.
Returns xs:date(fn:current-dateTime())
. This is an xs:date
(with timezone) that is current at some time during the evaluation of a query or
transformation in which fn:current-date
is executed.
This function is ·deterministic·. The precise instant during the query
or transformation represented by the value of fn:current-date
is ·implementation-dependent·.
The returned date will always have an associated timezone, which will always be the same as the implicit timezone in the dynamic context
fn:current-date()
returns an xs:date
corresponding to the
current date. For example, a call of fn:current-date()
might return
2004-05-12+01:00
.
Returns the current time.
fn:current-time
() as
xs:time
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on implicit timezone.
Returns xs:time(fn:current-dateTime())
. This is an xs:time
(with timezone) that is current at some time during the evaluation of a query or
transformation in which fn:current-time
is executed.
This function is ·deterministic·. The precise instant during the query
or transformation represented by the value of fn:current-time()
is ·implementation-dependent·.
The returned time will always have an associated timezone, which will always be the same as the implicit timezone in the dynamic context
fn:current-time()
returns an xs:time
corresponding to the
current time. For example, a call of fn:current-time()
might return
23:17:00.000-05:00
.
Returns the value of the implicit timezone property from the dynamic context.
fn:implicit-timezone
() as
xs:dayTimeDuration
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on implicit timezone.
Returns the value of the implicit timezone property from the dynamic context. Components of the dynamic context are described in Section C.2 Dynamic Context Components XP31.
Returns the value of the default collation property from the static context.
fn:default-collation
() as
xs:string
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on collations.
Returns the value of the default collation property from the static context. Components of the static context are described in Section C.1 Static Context Components XP31.
The default collation property can never be absent. If it is not explicitly defined,
a
system defined default can be invoked. If this is not provided, the Unicode codepoint
collation (http://www.w3.org/2005/xpath-functions/collation/codepoint
) is
used.
Returns the value of the default language property from the dynamic context.
fn:default-language
() as
xs:language
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on default language.
Returns the value of the default language property from the dynamic context. Components of the dynamic context are described in Section 2.1.2 Dynamic Context XP31.
The default language property can never be absent. The functions fn:format-integer
,
fn:format-date
, fn:format-time
, and fn:format-dateTime
are defined to use the default language if no explicit language is supplied. The default
language
may play a role in selection of a default collation, but this is not a requirement.
This function returns the value of the static base URI property from the static context.
fn:static-base-uri
() as
xs:anyURI?
This function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on static base URI.
The function returns the value of the static base URI property from the static context. If the property is absent, the empty sequence is returned.
Components of the static context are described in Section 2.1.1 Static Context XP31 .
XQuery 3.0 and XSLT 3.0 give an implementation freedom to use different base URIs
during
the static analysis phase and the dynamic evaluation phase, that is, for compile-time
and run-time resources respectively. This is appropriate when the implementation allows
the output of static analysis (a "compiled" query or stylesheet) to be deployed for
execution
to a different location from the one where static analysis took place. In this situation,
the
fn:static-base-uri
function should return a URI suitable for locating
resources needed during dynamic evaluation.
The functions included in this section operate on function items, that is, values referring to a function.
[Definition] Functions that accept functions among their arguments, or that return functions in their result, are described in this specification as higher-order functions. Some host languages may exclude higher-order functions from the set of functions that they support, or may include such functions in an optional conformance feature.
Note:
Some functions such as fn:parse-json
allow the option of supplying a callback function
for example to define exception behavior. Where this is not essential to the use of
the function,
the function has not been classified as higher-order for this purpose; in applications
where function items
cannot be created, these particular options will not be available.
| Function | Meaning |
|---|---|
fn:function-lookup |
Returns the function having a given name and arity, if there is one. |
fn:function-name |
Returns the name of the function identified by a function item. |
fn:function-arity |
Returns the arity of the function identified by a function item. |
Returns the function having a given name and arity, if there is one.
fn:function-lookup
($name
as
xs:QName
, $arity
as
xs:integer
) as
function(*)?
This function is ·deterministic·, ·context-dependent·, ·focus-dependent·, and ·higher-order·.
A call to fn:function-lookup
returns the function obtained by looking up
the expanded QName supplied as $name
and the arity supplied as
$arity
in the named functions component of the dynamic context
(specifically, the dynamic context of the call to fn:function-lookup
).
Furthermore, if that function has an implementation-dependent implementation (see
note
below), then the implementation of the function returned by
fn:function-lookup
is associated with the static and dynamic context of
the call to fn:function-lookup
.
Note:
The above rule deliberately uses the same wording as the corresponding rule for Named Function References. The term "a function [with] an implementation-dependent implementation" essentially means a function whose implementation is provided by the language processor rather than by the stylesheet or query author. This rule is therefore relevant to built-in functions and vendor-supplied extension functions whose result depends on the context of the function call.
Otherwise (if no known function can be identified by name and arity), an empty sequence is returned.
If the arguments to fn:function-lookup
identify a function that is present
in the static context of the function call, the function will always return the same
function that a static reference to this function would bind to. If there is no such
function in the static context, then the results depend on what is present in the
dynamic context, which is ·implementation-defined·.
This function can be useful where there is a need to make a dynamic decision on which of several statically-known functions to call. It can thus be used as a substitute for polymorphism, in the case where the application has been designed so several functions implement the same interface.
The function can also be useful in cases where a query or stylesheet module is written
to work with alternative versions of a library module. In such cases the author of
the
main module might wish to test whether an imported library module contains or does
not
contain a particular function, and to call a function in that module only if it is
available in the version that was imported. A static call would cause a static error
if
the function is not available, whereas getting the function using
fn:function-lookup
allows the caller to take fallback action in this
situation.
If the function that is retrieved by fn:function-lookup
is ·context-dependent·, that is, if it has
dependencies on the static or dynamic context of its caller, the context that applies
is
the static and/or dynamic context of the call to the fn:function-lookup
function itself. The context thus effectively forms part of the closure of the returned
function. In practice this applies only where the target of
fn:function-lookup
is a built-in function, because user-defined
functions never depend on the static or dynamic context of the function call. The
rule
applies recursively, since fn:function-lookup
is itself a context-dependent
built-in function.
These specifications do not define any circumstances in which the dynamic context will contain functions that are not present in the static context, but neither do they rule this out. For example an API may provide the ability to add functions to the dynamic context. Equally, these specifications do not define any mechanism for creating context-dependent functions other than the built-in context-dependent functions, but neither do they rule out the existence of such functions.
The mere fact that a function exists and has a name does not of itself mean that the
function is present in the dynamic context. For example, functions obtained through
use of the fn:load-xquery-module
function are not added to the dynamic context.
The expression fn:function-lookup(xs:QName('fn:substring'), 2)('abcd',
2)
returns 'bcd'
.
The expression (fn:function-lookup(xs:QName('xs:dateTimeStamp'), 1),
xs:dateTime#1)[1] ('2011-11-11T11:11:11Z')
returns an
xs:dateTime
value set to the specified date, time, and timezone; if
the implementation supports XSD 1.1 then the result will be an instance of the
derived type xs:dateTimeStamp
. The query is written to ensure that no
failure occurs when the implementation does not recognize the type
xs:dateTimeStamp
.
The expression let $f := fn:function-lookup(xs:QName('zip:binary-entry'), 2)
return if (exists($f)) then $f($href, $entry) else ()
returns the result of
calling zip:binary-entry($href, $entry)
if the function is available, or
an empty sequence otherwise.
Returns the name of the function identified by a function item.
fn:function-name
($func
as
function(*)
) as
xs:QName?
This function is ·deterministic·, ·context-independent·, ·focus-independent·, and ·higher-order·.
If $func
refers to a named function, fn:function-name($func)
returns the name of that function.
Otherwise ($func
refers to an anonymous function),
fn:function-name($func)
returns an empty sequence.
The prefix part of the returned QName is ·implementation-dependent·.
The expression fn:function-name(fn:substring#2)
returns fn:QName("http://www.w3.org/2005/xpath-functions",
"fn:substring")
. (The namespace prefix of the returned QName is not
predictable.)
The expression fn:function-name(function($node){count($node/*)})
returns ()
.
Returns the arity of the function identified by a function item.
fn:function-arity
($func
as
function(*)
) as
xs:integer
This function is ·deterministic·, ·context-independent·, ·focus-independent·, and ·higher-order·.
The fn:function-arity
function returns the arity (number of arguments) of
the function identified by $func
.
The expression fn:function-arity(fn:substring#2)
returns 2
.
The expression fn:function-arity(function($node){name($node)})
returns 1
.
The expression let $initial := fn:substring(?, 1, 1) return
fn:function-arity($initial)
returns 1
.
The following functions take function items as an argument.
| Function | Meaning |
|---|---|
fn:for-each |
Applies the function item $action to every item from the sequence $seq in turn, returning the concatenation of the resulting sequences in order. |
fn:filter |
Returns those items from the sequence $seq for which the supplied function $f returns true. |
fn:fold-left |
Processes the supplied sequence from left to right, applying the supplied function repeatedly to each item in turn, together with an accumulated result value. |
fn:fold-right |
Processes the supplied sequence from right to left, applying the supplied function repeatedly to each item in turn, together with an accumulated result value. |
fn:for-each-pair |
Applies the function item $action to successive pairs of items taken one from $seq1 and one from $seq2, returning the concatenation of the resulting sequences in order. |
fn:sort |
Sorts a supplied sequence, based on the value of a sort key supplied as a function. |
fn:apply |
Makes a dynamic call on a function with an argument list supplied in the form of an array. |
With all these functions, if the caller-supplied function fails with a dynamic error, this error is propagated as an error from the higher-order function itself.
Applies the function item $action to every item from the sequence $seq in turn, returning the concatenation of the resulting sequences in order.
fn:for-each
($seq
as
item()*
, $action
as
function(item()) as item()*
) as
item()*
This function is ·deterministic·, ·context-independent·, ·focus-independent·, and ·higher-order·.
The effect of the function is equivalent to the following implementation in XQuery:
declare function fn:for-each($seq, $action) { if (fn:empty($seq)) then () else ($action(fn:head($seq)), fn:for-each(fn:tail($seq), $action)) };
or its equivalent in XSLT:
<xsl:function name="fn:for-each"> <xsl:param name="seq"/> <xsl:param name="action"/> <xsl:if test="fn:exists($seq)"> <xsl:sequence select="$action(fn:head($seq)), fn:for-each(fn:tail($seq), $action)"/> </xsl:if> </xsl:function>
The function call fn:for-each($SEQ, $F)
is equivalent to the expression
for $i in $SEQ return $F($i)
, assuming that ordering mode is
ordered
.
The expression fn:for-each(1 to 5, function($a) { $a * $a })
returns (1, 4, 9, 16, 25)
.
The expression fn:for-each(("john", "jane"),
fn:string-to-codepoints#1)
returns (106, 111, 104, 110, 106, 97, 110, 101)
.
The expression fn:for-each(("23", "29"), xs:int#1)
returns (23, 29)
.
Returns those items from the sequence $seq for which the supplied function $f returns true.
fn:filter
($seq
as
item()*
, $f
as
function(item()) as xs:boolean
) as
item()*
This function is ·deterministic·, ·context-independent·, ·focus-independent·, and ·higher-order·.
The effect of the function is equivalent to the following implementation in XQuery:
declare function fn:filter( $seq as item()*, $f as function(item()) as xs:boolean) as item()* { if (fn:empty($seq)) then () else ( fn:head($seq)[$f(.) eq fn:true()], fn:filter(fn:tail($seq), $f) ) };
or its equivalent in XSLT:
<xsl:function name="fn:filter" as="item()*"> <xsl:param name="seq" as="item()*"/> <xsl:param name="f" as="function(item()) as xs:boolean"/> <xsl:if test="fn:exists($seq)"> <xsl:sequence select="fn:head($seq)[$f(.) eq fn:true()], fn:filter(fn:tail($seq), $f)"/> </xsl:if> </xsl:function>
As a consequence of the function signature and the function calling rules, a type
error
occurs if the supplied function $f returns anything other than a single
xs:boolean
item; there is no conversion to an effective boolean
value.
The function call fn:filter($SEQ, $F)
has a very similar effect to the
expression $SEQ[$F(.)]
. There are some differences, however. In the case of
fn:filter
, the function $F
is required to return a boolean;
there is no special treatment for numeric predicate values, and no conversion to an
effective boolean value. Also, with a filter expression $SEQ[$F(.)]
, the
focus within the predicate is different from that outside; this means that the use
of a
context-sensitive function such as fn:lang#1
will give different results in
the two cases.
The expression fn:filter(1 to 10, function($a) {$a mod 2 = 0})
returns (2, 4, 6, 8, 10)
.
The expression fn:filter((), fn:lang("en", ?))
returns ()
.
Processes the supplied sequence from left to right, applying the supplied function repeatedly to each item in turn, together with an accumulated result value.
fn:fold-left (
|
$seq |
as item()* ,
|
$zero |
as item()* ,
|
|
$f |
as function(item()*, item()) as item()* ) as item()* |
This function is ·deterministic·, ·context-independent·, ·focus-independent·, and ·higher-order·.
The effect of the function is equivalent to the following implementation in XQuery:
declare function fn:fold-left( $seq as item()*, $zero as item()*, $f as function(item()*, item()) as item()*) as item()* { if (fn:empty($seq)) then $zero else fn:fold-left(fn:tail($seq), $f($zero, fn:head($seq)), $f) };
or its equivalent in XSLT:
<xsl:function name="fn:fold-left" as="item()*"> <xsl:param name="seq" as="item()*"/> <xsl:param name="zero" as="item()*"/> <xsl:param name="f" as="function(item()*, item()) as item()*"/> <xsl:choose> <xsl:when test="fn:empty($seq)"> <xsl:sequence select="$zero"/> </xsl:when> <xsl:otherwise> <xsl:sequence select="fn:fold-left(fn:tail($seq), $f($zero, fn:head($seq)), $f)"/> </xsl:otherwise> </xsl:choose> </xsl:function>
As a consequence of the function signature and the function calling rules, a type error occurs if the supplied function $f cannot be applied to two arguments, where the first argument is either the value of $zero or the result of a previous application of $f, and the second is any single item from the sequence $seq.
This operation is often referred to in the functional programming literature as "folding" or "reducing" a sequence. It takes a function that operates on a pair of values, and applies it repeatedly, with an accumulated result as the first argument, and the next item in the sequence as the second argument. The accumulated result is initially set to the value of the $zero argument, which is conventionally a value (such as zero in the case of addition, one in the case of multiplication, or a zero-length string in the case of string concatenation) that causes the function to return the value of the other argument unchanged.
The expression fn:fold-left(1 to 5, 0, function($a, $b) { $a + $b
})
returns 15
. (This returns the sum of the items in the sequence).
The expression fn:fold-left((2,3,5,7), 1, function($a, $b) { $a * $b
})
returns 210
. (This returns the product of the items in the sequence).
The expression fn:fold-left((true(), false(), false()), false(), function($a, $b) {
$a or $b })
returns true()
. (This returns true if any item in the sequence has an effective boolean
value of true).
The expression fn:fold-left((true(), false(), false()), false(), function($a, $b) {
$a and $b })
returns false()
. (This returns true only if every item in the sequence has an effective
boolean value of true).
The expression fn:fold-left(1 to 5, (), function($a, $b) {($b,
$a)})
returns (5,4,3,2,1)
. (This reverses the order of the items in a sequence).
The expression fn:fold-left(1 to 5, "", fn:concat(?, ".", ?))
returns ".<IP_ADDRESS>.5"
.
The expression fn:fold-left(1 to 5, "$zero", fn:concat("$f(", ?, ", ", ?, ")"))
returns "$f($f($f($f($f($zero, 1), 2), 3), 4), 5)"
.
The expression fn:fold-left(1 to 5, map{}, function($map, $n) {map:put($map, $n, $n*2)})
returns map{1:2, 2:4, 3:6, 4:8, 5:10}
.
Processes the supplied sequence from right to left, applying the supplied function repeatedly to each item in turn, together with an accumulated result value.
fn:fold-right (
|
$seq |
as item()* ,
|
$zero |
as item()* ,
|
|
$f |
as function(item(), item()*) as item()* ) as item()* |
This function is ·deterministic·, ·context-independent·, ·focus-independent·, and ·higher-order·.
The effect of the function is equivalent to the following implementation in XQuery:
declare function fn:fold-right( $seq as item()*, $zero as item()*, $f as function(item(), item()*) as item()*) as item()* { if (fn:empty($seq)) then $zero else $f(fn:head($seq), fn:fold-right(fn:tail($seq), $zero, $f)) };
or its equivalent in XSLT:
<xsl:function name="fn:fold-right" as="item()*"> <xsl:param name="seq" as="item()*"/> <xsl:param name="zero" as="item()*"/> <xsl:param name="f" as="function(item(), item()*) as item()*"/> <xsl:choose> <xsl:when test="fn:empty($seq)"> <xsl:sequence select="$zero"/> </xsl:when> <xsl:otherwise> <xsl:sequence select="$f(fn:head($seq), fn:fold-right(fn:tail($seq), $zero, $f))"/> </xsl:otherwise> </xsl:choose> </xsl:function>
As a consequence of the function signature and the function calling rules, a type error occurs if the supplied function $f cannot be applied to two arguments, where the first argument is any item in the sequence $seq, and the second is either the value of $zero or the result of a previous application of $f.
This operation is often referred to in the functional programming literature as "folding" or "reducing" a sequence. It takes a function that operates on a pair of values, and applies it repeatedly, with the next item in the sequence as the first argument, and the result of processing the remainder of the sequence as the second argument. The accumulated result is initially set to the value of the $zero argument, which is conventionally a value (such as zero in the case of addition, one in the case of multiplication, or a zero-length string in the case of string concatenation) that causes the function to return the value of the other argument unchanged.
In cases where the function performs an associative operation on its two arguments
(such
as addition or multiplication), fn:fold-right
produces the same result as
fn:fold-left
.
The expression fn:fold-right(1 to 5, 0, function($a, $b) { $a + $b
})
returns 15
. (This returns the sum of the items in the sequence).
The expression fn:fold-right(1 to 5, "", fn:concat(?, ".", ?))
returns "<IP_ADDRESS>.5."
.
The expression fn:fold-right(1 to 5, "$zero", concat("$f(", ?, ", ", ?,
")"))
returns "$f(1, $f(2, $f(3, $f(4, $f(5, $zero)))))"
.
Applies the function item $action to successive pairs of items taken one from $seq1 and one from $seq2, returning the concatenation of the resulting sequences in order.
fn:for-each-pair (
|
$seq1 |
as item()* ,
|
$seq2 |
as item()* ,
|
|
$action |
as function(item(), item()) as item()* ) as item()* |
This function is ·deterministic·, ·context-independent·, ·focus-independent·, and ·higher-order·.
The effect of the function is equivalent to the following implementation in XQuery:
declare function fn:for-each-pair($seq1, $seq2, $action) { if(fn:exists($seq1) and fn:exists($seq2)) then ( $action(fn:head($seq1), fn:head($seq2)), fn:for-each-pair(fn:tail($seq1), fn:tail($seq2), $action) ) else () };
or its equivalent in XSLT:
<xsl:function name="fn:for-each-pair"> <xsl:param name="seq1"/> <xsl:param name="seq2"/> <xsl:param name="action"/> <xsl:if test="fn:exists($seq1) and fn:exists($seq2)"> <xsl:sequence select="$action(fn:head($seq1), fn:head($seq2))"/> <xsl:sequence select="fn:for-each-pair(fn:tail($seq1), fn:tail($seq2), $action)"/> </xsl:if> </xsl:function>
If one sequence is longer than the other, excess items in the longer sequence are ignored.
The expression fn:for-each-pair(("a", "b", "c"), ("x", "y", "z"),
concat#2)
returns ("ax", "by", "cz")
.
The expression fn:for-each-pair(1 to 5, 1 to 5, function($a, $b){10*$a + $b})
returns (11, 22, 33, 44, 55)
.
The expression let $s := 1 to 8 return fn:for-each-pair($s, tail($s), function($a, $b){$a*$b})
returns (2, 6, 12, 20, 30, 42, 56)
.
Sorts a supplied sequence, based on the value of a sort key supplied as a function.
fn:sort
($input
as
item()*
) as
item()*
fn:sort
($input
as
item()*
, $collation
as
xs:string?
) as
item()*
fn:sort (
|
$input |
as item()* ,
|
$collation |
as xs:string? ,
|
|
$key |
as function(item()) as xs:anyAtomicType* ) as item()* |
The one-argument form of this function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on collations.
The two-argument form of this function is ·deterministic·, ·context-dependent·, and ·focus-independent·. It depends on collations.
The three-argument form of this function is ·deterministic·, ·context-dependent·, ·focus-independent·, and ·higher-order·. It depends on collations.
Calling the single-argument version of the function is equivalent to calling the two-argument
form
with default-collation()
as the second argument: that is, it sorts a sequence of items according
to the typed value of the items, using the default collation to compare strings.
Calling the two-argument version of the function is equivalent to calling the three-argument
form
with fn:data#1
as the third argument: that is, it sorts a sequence of items according
to the typed value of the items, using a specified collation to compare strings.
In the case of both fn:sort#2
and fn:sort#3
, supplying an empty
sequence as the second argument is equivalent to supplying fn:default-collation()
. For more
information on collations see 5.3.5 Choosing a collation.
The result of the function is obtained as follows:
For each item in the sequence $input
, the function supplied as $key
is evaluated with that item as its argument.
The resulting values are the sort keys of the items in the input sequence.
The result sequence contains the same items as the input sequence $input
, but generally in a different order.
Let $C be the selected collation, or the default collation where applicable.
The order of items in the result is such that, given two items $A
and $B
:
If (fn:deep-equal($key($A), $key($B), $C)
, then the relative order of $A
and $B
in the output is the same as their relative order in the input (that is, the sort
is stable)
Otherwise, if (deep-less-than($key($A), $key($B), $C)
, then $A
precedes $B
in the output.
The function deep-less-than
is defined as the boolean result of the expression:
if (fn:empty($A))
then fn:exists($B)
else if (fn:deep-equal($A[1], $B[1], $C))
then deep-less-than(fn:tail($A), fn:tail($B), $C)
else if ($A[1] ne $A[1] (:that is, $A[1] is NaN:))
then fn:true()
else if (is-string($A[1]) and is-string($B[1])
then fn:compare($A[1], $B[1], $C) lt 0
else $A[1] lt $B[1]
where the function is-string($X)
returns true if and only if $X
is an instance of
xs:string
, xs:anyURI
, or xs:untypedAtomic
.
This ordering of sequences is referred to by mathematicians as "lexicographic ordering".
If the set of computed sort keys contains values that are not comparable using the
lt
operator then the sort
operation will fail with a type error ([err:XPTY0004]XP31).
XSLT and XQuery both provide native sorting capability, but previous releases of XPath provided no sorting functionality for use in standalone environments.
In addition there are cases where this function may be more flexible than the built-in sorting capability for XQuery or XSLT, for example when the sort key or collation is chosen dynamically, or when the sort key is a sequence of items rather than a single item.
The results are compatible with the results of XSLT sorting (using xsl:sort
) in the case where the sort key evaluates to a sequence of
length zero or one, given the options stable="yes"
and order="ascending"
.
The results are compatible with the results of XQuery sorting (using the order by
clause) in the case where the sort key evaluates to a sequence of
length zero or one, given the options stable
, ascending
, and empty least
.
The expression fn:sort((1, 4, 6, 5, 3))
returns (1, 3, 4, 5, 6)
.
The expression fn:sort((1, -2, 5, 10, -10, 10, 8), (), fn:abs#1)
returns (1, -2, 5, 8, 10, -10, 10)
.
To sort a set of strings $in
using Swedish collation:
let $SWEDISH := "http://www.w3.org/2013/collation/UCA?lang=se" return fn:sort($in, $SWEDISH)
To sort a sequence of employees by last name as the major sort key and first name as the minor sort key, using the default collation:
fn:sort($employees, (), function($emp) {$emp/name ! (last, first)})
Makes a dynamic call on a function with an argument list supplied in the form of an array.
fn:apply
($function
as
function(*)
, $array
as
array(*)
) as
item()*
This function is ·deterministic·, ·context-independent·, ·focus-independent·, and ·higher-order·.
The result of the function is obtained by invoking the supplied function $function
with arguments
taken from the members of the supplied array $array
. The first argument of the function call is the first
member of $array
, the second argument is the second member of $array
, and so on.
The arity of the supplied function $function
must be the same as the size of the array $array
.
The effect of calling fn:apply($f, [$a, $b, $c, ...])
is the same as the effect of the dynamic function call
$f($a, $b, $c, ....)
. For example, the function conversion rules are applied to the supplied arguments
in the usual way.
A dynamic error is raised if the arity of the function $function
is not the same as the size of the
array $array
([err:FOAP0001]).
The function is useful where the arity of a function item is not known statically.
The expression fn:apply(fn:concat#3, ["a", "b", "c"])
returns "abc"
.
The expression fn:apply($f, array:subarray(["a", "b", "c", "d", "e", "f"], 1, fn:function-arity($f)))
calls the supplied function $f
supplying the number of arguments required by its arity.
The following functions allow dynamic loading and execution of XQuery queries and XSLT stylesheets.
| Function | Meaning |
|---|---|
fn:load-xquery-module |
Provides access to the public functions and global variables of a dynamically-loaded XQuery library module. |
fn:transform |
Invokes a transformation using a dynamically-loaded XSLT stylesheet. |
Provides access to the public functions and global variables of a dynamically-loaded XQuery library module.
fn:load-xquery-module
($module-uri
as
xs:string
) as
map(*)
fn:load-xquery-module
($module-uri
as
xs:string
, $options
as
map(*)
) as
map(*)
This function is ·deterministic·, ·context-dependent·, ·focus-independent·, and ·higher-order·.
The function loads an implementation-defined set of modules having the target namespace
$module-uri
.
Calling the one-argument version of the function has the same effect as calling the two-argument version with an empty map as the second argument.
The $options
argument can be used to control the way in which the function operates.
The ·option parameter conventions· apply.
| Key | Meaning |
|---|---|
xquery-version |
The minimum level of the XQuery language that the
processor must support.
|
location-hints |
A sequence of URIs (in the form of xs:string values) which may be used or ignored in an
·implementation-defined· way.
|
context-item |
The item to be used as the initial context item when evaluating global variables in
the library module. Supplying
an empty sequence is equivalent to omitting the entry from the map, and indicates
the absence of a context item.
If the library module specifies a required type for the context item, then the supplied
value must conform to
this type, without conversion.
|
variables |
Values for external variables defined in the library module. Values must be supplied
for external variables that have no default value, and may be supplied for external variables
that do have a default value. The supplied value must conform to the required type of the variable, without conversion.
The map contains one entry for each external variable: the key is the variable's name,
and the associated value is
the variable's value. The ·option parameter conventions· do not apply
to this contained map.
|
vendor-options |
Values for vendor-defined configuration options for the XQuery processor used to process
the request. The key is the
name of an option, expressed as a QName: the namespace URI of the QName should be a URI controlled
by the vendor of the XQuery processor. The meaning of the associated value is ·implementation-defined·.
Implementations should ignore options whose names are in an unrecognized namespace.
The ·option parameter conventions· do not apply
to this contained map.
|
The result of the function is a map R with two entries:
There is an entry whose key is the xs:string
value "variables"
and whose associated value
is a map V. This map (V) contains one entry for each public global variable declared in the library module.
The key of the
entry is the name of the variable, as an xs:QName
value; the associated value is the value of the variable.
There is an entry whose key is the xs:string
value "functions"
and whose associated value
is a map F. This map (F) contains one entry for each public function declared in the library module, except
that when two functions
have the same name (but different arity), they share the same entry. The key of the
entry is the name of the function(s), as an xs:QName
value; the associated value is a map A.
This map (A) contains one entry for each function with the given name; its key is the arity of
the function,
as an xs:integer
value, and its associated value is the function itself, as a function item. The function
can be invoked using the rules for dynamic function invocation.
The static and dynamic context of the library module are established according to the rules in Section C Context Components XQ31.
It is ·implementation-defined· whether constructs in the library module are evaluated in the same ·execution scope· as the calling module.
The library module that is loaded may import other modules using an import module
declaration. The result of
fn:load-xquery-module
does not include global variables or functions declared in such a transitively-imported
module.
However, the options
map supplied in the function call may
(and if no default is defined, must)
supply values for external variables declared in transitively-loaded library modules.
The library module that is loaded may import schema declarations using an import schema
declaration. It is
·implementation-defined· whether schema components in the in-scope
schema definitions of the calling module
are automatically added to the in-scope schema definitions of the dynamically loaded
module. The in-scope schema definitions
of the calling and called modules must be consistent, according to the rules defined
in
Section
2.2.5 Consistency Constraints
XQ31.
Where nodes are passed to or from the dynamically loaded module, for example as an argument or result of a function, they should if possible retain their node identity, their base URI, their type annotations, and their relationships to all other nodes in the containing tree (including ancestors and siblings). If this is not possible, for example because the only way of passing nodes to the chosen XQuery implementation is by serializing and re-parsing, then a node may be passed in the form of a deep copy, which may lose information about the identity of the node, about its ancestors and siblings, about its base URI, about its type annotations, and about its relationships to other nodes passed across the interface.
If $module-uri
is a zero length string, a dynamic error is raised [err:FOQM0001].
If the implementation is not able to find a library module with the specified target namespace, an error is raised [err:FOQM0002].
If a static error (including a statically-detected type error) is encountered when processing the library module, a dynamic error is raised [err:FOQM0003].
If a value is supplied for the initial context item or for an external variable and the value does not conform to the required type declared in the dynamically loaded module, a dynamic error is raised [err:FOQM0005].
If no suitable XQuery processor is available, a dynamic error is raised [err:FOQM0006]. This includes (but is not limited to) the following cases:
No XQuery processor is available;
Use of the function has been disabled;
No XQuery processor supporting the requested version of XQuery is available;
No XQuery processor supporting the optional Module Feature is available.
If a dynamic error (including a dynamically-detected type error) is encountered when processing the module (for example, when evaluating its global variables), the dynamic error is returned as is.
As with all other functions in this specification, conformance requirements depend on the host language. For example, a host language might specify that provision of this function is optional, or that it is excluded entirely, or that implementations are required to support XQuery modules using a specified version of XQuery.
Even where support for this function is mandatory, it is recommended for security reasons that implementations should provide a user option to disable its use, or to disable aspects of its functionality.
Invokes a transformation using a dynamically-loaded XSLT stylesheet.
fn:transform
($options
as
map(*)
) as
map(*)
This function is ·nondeterministic·, ·context-dependent·, and ·focus-independent·.
This function loads an XSLT stylesheet and invokes it to perform a transformation.
The inputs to the transformation are supplied in the form of a map. The ·option parameter conventions· apply to this map; they do not apply to any nested map unless otherwise specified.
The function first identifies the requested XSLT version, as follows:
If the xslt-version
option is present, the requested XSLT version is the value of that option.
Otherwise, the requested XSLT version
is the value of the [xsl:]version
attribute of the outermost element in the supplied stylesheet or package.
The function then attempts to locate an XSLT processor that implements the requested XSLT version.
If a processor that implements the requested XSLT version is available, then it is used.
Otherwise, if a processor that implements a version later than the requested version is available, then it is used.
Otherwise, the function fails indicating that no suitable XSLT processor is available.
Note:
The phrase locate an XSLT processor includes the possibility of locating a software product and configuring it to act as an XSLT processor that implements the requested XSLT version.
If more than one XSLT processor is available under the above rules, then the one that is chosen may be selected according to the availability of requested features: see below.
Once an XSLT processor has been selected that implements a given version of XSLT,
the processor
follows the rules of that version of the XSLT specification. This includes any decision
to operate in backwards or forwards
compatibility mode. For example, if an XSLT 2.0 processor is selected, and the stylesheet
specifies version="1.0"
,
then the processor will operate in backwards compatibility mode; if the same processor
is selected and the stylesheet
specifies version="3.0"
, the processor will operate in forwards compatibility mode.
The combinations of options that are relevant to each version of XSLT, other than
xslt-version
itself, are listed below. This is followed by a table giving the meaning of each option.
For invocation of an XSLT 1.0 processor (see [XSL Transformations (XSLT) Version 1.0]), the supplied options must include all of the following (if anything else is present, it is ignored):
The stylesheet, provided by supplying exactly one of the following:
stylesheet-location
stylesheet-node
stylesheet-text
The source tree, provided as the value of the source-node
option.
Zero or more of the following additional options:
stylesheet-base-uri
stylesheet-params
(defaults to an empty map)initial-mode
(defaults to the unnamed mode)delivery-format
(defaults todocument
)serialization-params
(defaults to an empty map)enable-messages
(default is implementation-defined)requested-properties
(default is an empty map)vendor-options
(defaults to an empty map)cache
(default is implementation-defined)
For invocation of an XSLT 2.0 processor (see [XSL Transformations (XSLT) Version 2.0]), the supplied options must include all of the following (if anything else is present, it is ignored):
The stylesheet, provided by supplying exactly one of the following:
stylesheet-location
stylesheet-node
stylesheet-text
Invocation details, as exactly one of the following:
For apply-templates invocation, all of the following:
source-node
Optionally, initial-mode
(defaults to the unnamed mode)
For call-template invocation, all of the following:
initial-template
Optionally, source-node
Zero or more of the following additional options:
stylesheet-base-uri
stylesheet-params
(defaults to an empty map)base-output-uri
(defaults to absent)delivery-format
(defaults todocument
)serialization-params
(defaults to an empty map)enable-messages
(default is implementation-defined)enable-trace
(default is implementation-defined)requested-properties
(default is an empty map)vendor-options
(defaults to an empty map)cache
(default is implementation-defined)
For invocation of an XSLT 3.0 processor (see [XSL Transformations (XSLT) Version 3.0]), the supplied options must include all of the following (if anything else is present, it is ignored):
The stylesheet, provided either by supplying exactly one of the following:
stylesheet-location
stylesheet-node
stylesheet-text
Or by supplying exactly one of the following:
package-location
package-node
package-text
package-name
plus optionallypackage-version
Invocation details, as exactly one of the following combinations:
For apply-templates invocation, all of the following:
Exactly one of source-node
or initial-match-selection
Optionally, initial-mode
Optionally, template-params
Optionally, tunnel-params
For call-template invocation using an explicit template name, all of the following:
initial-template
Optionally, template-params
Optionally, tunnel-params
Optionally, source-node
For call-template invocation using the defaulted template name xsl:initial-template
, all of the following:
Optionally, template-params
Optionally, tunnel-params
Note:
If the source-node
option is present and initial-template
is absent,
then apply-templates invocation will be used. To use call-template invocation on the
template
named xsl:initial-template
while also supplying a context item for use when evaluating
global variables, either (a) supply the context item using the global-context-item
option,
or (b) supply source-node
, and set the initial-template
option explicitly to the
QName xsl:initial-template
For call-function invocation, all of the following:
initial-function
function-params
Note:
The invocation method can be determined as the first of the following which applies:
If initial-function
is present, then call-function invocation.
If initial-template
is present, then call-template invocation.
If source-node
or initial-match-selection
is present, then apply-templates invocation.
Otherwise, call-template
invocation using
the default entry point xsl:initial-template
.
Zero or more of the following additional options:
stylesheet-base-uri
static-params
(defaults to an empty map)stylesheet-params
(defaults to an empty map)global-context-item
(defaults to absent)base-output-uri
(defaults to absent)delivery-format
serialization-params
(defaults to an empty map)enable-assertions
(default is false)enable-messages
(default is implementation-defined)enable-trace
(default is implementation-defined)requested-properties
(default is an empty map)vendor-options
(defaults to an empty map)cache
(default is implementation-defined)
The meanings of each option are defined in the table below.
| Key | Applies to | Value | Meaning |
|---|---|---|---|
base-output-uri |
1.0, 2.0, 3.0 | The URI of the principal result document; also used as the base URI for
resolving relative URIs of secondary result documents. If the value is a relative
reference, it is resolved against the static base URI of the fn:transform
function call.
|
|
cache |
1.0, 2.0, 3.0 | This option has no effect on the result of the transformation but may affect
efficiency. The value true indicates an expectation that the same
stylesheet is likely to be used for more than one transformation; the value
false indicates an expectation that the stylesheet will be used once
only.
|
|
delivery-format |
1.0, 2.0, 3.0 | The manner in which the transformation results should be delivered. Applies both to
the
principal result document and to secondary result documents created using
xsl:result-document .
|
|
document |
The result is delivered as a document node. | ||
serialized |
The result is delivered as
a string, representing the results of serialization. Note that (as with the
fn:serialize function) the final encoding stage of
serialization (which turns a sequence of characters into a sequence of
octets) is either skipped, or reversed by decoding the octet stream back
into a character stream.
|
||
raw |
The result of the initial template or function is returned as an arbitrary XDM value (after conversion to the declared type, but without wrapping in a document node, and without serialization): when this option is chosen, the returned map contains the raw result. | ||
enable-assertions |
3.0 | Indicates whether any xsl:assert instructions in the stylesheet
are to be evaluated.
|
|
enable-messages |
1.0, 2.0, 3.0 | Indicates whether any xsl:message instructions in the stylesheet
are to be evaluated. The destination and formatting of any such messages is
implementation-defined.
|
|
enable-trace |
2.0, 3.0 | Indicates whether any fn:trace functions in the stylesheet are to
generate diagnostic messages. The destination and formatting of any such messages
is
implementation-defined.
|
|
function-params |
3.0 | An array of values to be used as the arguments to the initial function call.
The value is converted to the required type of the declared parameter using the function
conversion rules.
|
|
global-context-item |
3.0 | The value of the global context item, as defined in XSLT 3.0
|
|
initial-function |
3.0 | The name of the initial function to be called for call-function invocation. The
arity of the function is inferred from the length of
function-params .
|
|
initial-match-selection |
3.0 | The value of the initial match selection, as defined in XSLT 3.0
|
|
initial-mode |
1.0, 2.0, 3.0 | The name of the initial processing mode.
|
|
initial-template |
2.0, 3.0 | The name of a named template in the stylesheet to act as the initial entry
point.
|
|
package-name |
3.0 | The name of the top-level stylesheet package to be invoked (an absolute
URI)
|
|
package-location |
3.0 | The location of the top-level stylesheet package, as a relative or absolute
URI
|
|
package-node |
3.0 | A document or element node containing the top-level stylesheet
package
|
|
package-text |
3.0 | The top-level stylesheet package in the form of unparsed lexical
XML.
|
|
package-version |
3.0 | The version of the top-level stylesheet package to be invoked.
|
|
post-process |
1.0 2.0 3.0 | A function that is used to post-process each result document of
the transformation (both the principal result and secondary results), in whatever
form it would otherwise be delivered (document, serialized, or raw). The first
argument of the function is the key used to identify the result in the map return
by the fn:transform function (for example, this will be the supplied
base output URI in the case of the principal result, or the string "output" if no
base output URI was supplied). The second argument is the
actual value. The value that is returned in the result of the fn:transform
function is the result of applying this post-processing.
Note: If the implementation provides a way of writing or invoking functions
with side-effects, this post-processing function might be used to save
a copy of the result document to persistent storage. For example, if the
implementation provides access to the EXPath File library [EXPath],
then a serialized document might be written to filestore by calling the
If the primary purpose of the post-processing function is achieved by
means of such side-effects, and if the actual results are not needed by
the caller of the Calls to
|
|
requested-properties |
1.0, 2.0, 3.0 | The keys in the map are QNames that could legitimately be supplied in a call to
the XSLT system-property function; the values in the map are the requested
settings of the corresponding property. The boolean values true() and
false() are equivalent to the string values yes and
no . As a special case, setting a value for xsl:version has
no effect, because of the potential for conflict with other options. For example:
xsl:supports-dynamic-evaluation
to false() is interpreted as an explicit request for a processor in which
the value of the property is false. The effect if the requests cannot be precisely
met
is implementation-defined. In some cases it may be appropriate to ignore the request
or
to provide an alternative (for example, a later version of the product than the one
requested); in other cases it may be more appropriate to raise an error [err:FOXT0001] indicating that no suitable XSLT processor
is available.
|
|
serialization-params |
1.0, 2.0, 3.0 | Serialization parameters for the principal result document. The supplied map
follows the same rules that apply to a map supplied as the second argument of
fn:serialize .
|
|
source-node |
1.0, 2.0, 3.0 | When source-node is supplied then the
global-context-item (the context item for evaluating global variables)
is the root of the tree containing the supplied node. In addition, for apply-templates
invocation, the source-node acts as the
initial-match-selection , that is, stylesheet execution starts by
applying templates to this node.
|
|
static-params |
3.0 | The values of static parameters defined in the stylesheet; the keys are the
names of the parameters, and the associated values are their values. The value is
converted to the required type of the declared parameter using the function conversion
rules.
|
|
stylesheet-base-uri |
1.0, 2.0, 3.0 | A string intended to be used as the static base URI of the principal stylesheet
module. This value must be used if no other static base URI is
available. If the supplied stylesheet already has a base URI (which will generally
be
the case if the stylesheet is supplied using stylesheet-node or
stylesheet-location ) then it is ·implementation-defined· whether this
parameter has any effect. If the value is a relative reference, it is resolved against
the static base URI of the fn:transform function call.
|
|
stylesheet-location |
1.0, 2.0, 3.0 | URI that can be used to locate the principal stylesheet module. If relative, it
is resolved against the static base URI of the fn:transform function call.
The value also acts as the default for stylesheet-base-uri.
|
|
stylesheet-node |
1.0, 2.0, 3.0 | Root of the tree containing the principal stylesheet module, as a document or
element node. The base URI of the node acts as the default for
stylesheet-base-uri.
|
|
stylesheet-params |
1.0, 2.0, 3.0 | A map holding values to be supplied for stylesheet parameters. The keys are the
parameter names; the values are the corresponding parameter values. The values are
converted if necessary to the required type using the function conversion rules. The
default is an empty map.
|
|
stylesheet-text |
1.0, 2.0, 3.0 | The principal stylesheet module in the form of unparsed lexical
XML.
|
|
template-params |
3.0 | The values of non-tunnel parameters to be supplied to the initial template,
used with both apply-templates and call-template invocation. Each value is converted
to
the required type of the declared parameter using the function conversion
rules.
|
|
tunnel-params |
3.0 | The values of tunnel parameters to be supplied to the initial template, used
with both apply-templates and call-template invocation. Each value is converted to
the
required type of the declared parameter using the function conversion
rules.
|
|
vendor-options |
1.0, 2.0, 3.0 | Values for vendor-defined configuration options for the XSLT processor used to
process the request. The key is the name of an option, expressed as a QName: the
namespace URI of the QName should be a URI controlled by the vendor
of the XSLT processor. The meaning of the associated value is ·implementation-defined·. Implementations
should ignore options whose names are in an unrecognized
namespace. Default is an empty map.
|
|
xslt-version |
1.0, 2.0, 3.0 | The minimum level of the XSLT language that the processor must support.
|
The result of the transformation is returned as a map. There is one entry in the map
for the principal result document, and one
for each secondary result document. The key is a URI in the form of an xs:string
value. The key for the principal
result document is the base output URI if specified, or the string "output"
otherwise. The key for secondary
result documents is the URI of the document, as an absolute URI. The associated value
in each entry depends on the requested
delivery format. If the delivery format is document
, the value is a document node. If the delivery format is
serialized
, the value is a string containing the serialized result. If the delivery format is
saved
,
the value is the absolute URI of the location where the serialized result has been
saved. The saved document will not be accessible
at this location within the current ·execution scope·
(this is to prevent any dependency on order of execution).
Where nodes are passed to or from the transformation, for example as the value of a stylesheet parameter or the result of a function, they should if possible retain their node identity, their base URI, their type annotations, and their relationships to all other nodes in the containing tree (including ancestors and siblings). If this is not possible, for example because the only way of passing nodes to the chosen XSLT implementation is by serializing and re-parsing, then a node may be passed in the form of a deep copy, which may lose information about the identity of the node, about its ancestors and siblings, about its base URI, about its type annotation, and about its relationships to other nodes passed across the interface.
It is ·implementation-defined· whether the XSLT transformation is executed within the same ·execution scope· as the calling code.
The function is ·nondeterministic· in that it is
·implementation-dependent· whether running the function twice against the same
inputs produces identical results. The results of two invocations may differ in the
identity of any returned nodes; they may also
differ in other respects, for example because the value of fn:current-dateTime
is different for the two invocations,
or because the contents of external documents accessed using fn:doc
or xsl:source-document
change between
one invocation and the next.
The delivery format saved
indicates that the transformation should modify the state of the external environment.
This has two noteworthy consequences:
It creates a potential security risk.
The fn:transform
function ceases to be a pure function, because it has side-effects.
Implementations may mitigate these problems in a number of ways, including the following:
Use of the delivery-format=saved
option may be disallowed, either
completely or at user option.
The environment that the delivery-format=saved
option is allowed to modify may be
sand-boxed in some way. For example: resources that are created using this option
may be accessible only
via some special interface; the resource may become available only on completion of
the execution scope
in which the fn:transform function is evaluated; or the implementation may prevent
the use functions
such as fn:doc
and fn:collection
to access such resources.
Creating multiple resources with the same URI may be disallowed.
The implementation may define circumstances in which the side-effect of creating external resources is thwarted as a consequence of query optimization (for example, any situation in which a query calls fn:transform but has no functional dependency on the result of the call).
There may be restrictions on the URIs that can be used to identify saved resources
A dynamic error is raised [err:FOXT0001] if the transformation cannot be invoked because no suitable XSLT processor is available. This includes (but is not limited to) the following cases:
No XSLT processor is available;
No XSLT processor supporting the requested version of XSLT is available;
The XSLT processor API does not support some requested feature (for example, the ability to supply tunnel parameters externally);
A dynamic error is raised [err:FOXT0002] if an error is detected in the supplied parameters (for example if two mutually-exclusive parameters are supplied).
If a static or dynamic error is reported by the XSLT processor, this function fails with a dynamic error, retaining the XSLT error code.
A dynamic error is raised [err:FOXT0003] if the XSLT transformation invoked by a call on
fn:transform
fails with a static or dynamic error, and no more specific error code is available.
Note:
XSLT 1.0 does not define any error codes, so this is the likely outcome with an XSLT 1.0 processor. XSLT 2.0 and 3.0 do define error codes, but some APIs do not expose them. If multiple errors are signaled by the transformation (which is most likely to happen with static errors) then the error code should where possible be that of one of these errors, chosen arbitrarily; the processor may make details of additional errors available to the application in an ·implementation-defined· way.
A dynamic error is raised [err:FOXT0004] if the use of this function (or of selected options) has been externally disabled, for example for security reasons.
A dynamic error is raised [err:FOXT0005] if delivery-format
is saved
and the results cannot be saved at the specified location.
A dynamic error is raised [err:FOXT0006] if the transformation produces output containing characters available only in XML 1.1, and the calling processor cannot handle such characters.
A dynamic error is raised [err:FOXT0007] if the option delivery-format:saved
is used in a way that violates any implementation-defined restrictions on its use.
Recursive use of the fn:transform
function may lead to catastrophic failures such as
non-termination or stack overflow. No error code is assigned to such conditions, since
they cannot necessarily
be detected by the processor.
As with all other functions in this specification, conformance requirements depend
on the host language.
For example, a host language might specify that provision of this function is optional,
or that it is excluded entirely,
or that implementations are required to support a particular set of values for the
xslt-version
parameter.
Even where support for this function is mandatory, it is recommended for security reasons that implementations should provide a user option to disable its use, or to disable aspects of its functionality such as the ability to write to persistent resources.
The following example loads a stylesheet from the location render.xsl
,
applies it to a document loaded from test.xml
, and uses an XPath expression
to examine the result:
let $result := fn:transform( map { "stylesheet-location" : "render.xsl", "source-node" : fn:doc('test.xml') }) return $result?output//body
Maps and arrays are introduced as new datatypes in XDM 3.1. This section describes functions that operate on maps and arrays. It also describes functions that operate on JSON data structures, which make extensive use of maps and arrays.
The functions defined in this section use a conventional namespace prefix map
, which
is assumed to be bound to the namespace URI http://www.w3.org/2005/xpath-functions/map
.
A map is an additional kind of item.
[Definition] A map consists of a set of entries. Each entry comprises a key which is an arbitrary atomic value, and an arbitrary sequence called the associated value.
[Definition] Within a map, no two entries have the same key.
Two atomic values K1
and K2
are the same key
for this purpose if the (internal) function call op:same-key($K1, $K2)
returns true.
It is not necessary that all the keys in a map should be of the same type (for example, they can include a mixture of integers and strings).
As with all other values, the functions in this specification treat maps as immutable.
For example, the map:remove
function returns a map that differs
from the supplied map by the omission (typically) of one entry, but the supplied map
is not changed by the operation.
Two calls on map:remove
with the same arguments return maps that are
indistinguishable from each other; there is no way of asking whether these are "the
same map".
The function call map:get($map, $key)
can be used to retrieve the value associated with a given key.
A map can also be viewed as a function from keys to associated values. To achieve
this, a map is also a
function item. The function corresponding to the map has the signature
function($key as xs:anyAtomicValue) as item()*
. Calling the function has the same effect as calling
the get
function: the expression
$map($key)
returns the same result as get($map, $key)
. For example, if $books-by-isbn
is a map whose keys are ISBNs and whose assocated values are book
elements, then the expression
$books-by-isbn("0470192747")
returns the book
element with the given ISBN.
The fact that a map is a function item allows it to be passed as an argument to higher-order
functions
that expect a function item as one of their arguments.
There is no operation to atomize a map or convert it to a string. The function fn:serialize
can in some cases
be used to produce a JSON representation of a map.
| Function | Meaning |
|---|---|
op:same-key |
Determines whether two atomic values can coexist as separate keys within a map. |
map:merge |
Returns a map that combines the entries from a number of existing maps. |
map:size |
Returns the number of entries in the supplied map. |
map:keys |
Returns a sequence containing all the keys present in a map |
map:contains |
Tests whether a supplied map contains an entry for a given key |
map:get |
Returns the value associated with a supplied key in a given map. |
map:find |
Searches the supplied input sequence and any contained maps and arrays for a map entry with the supplied key, and returns the corresponding values. |
map:put |
Returns a map containing all the contents of the supplied map, but with an additional entry, which replaces any existing entry for the same key. |
map:entry |
Returns a map that contains a single entry (a key-value pair). |
map:remove |
Returns a map containing all the entries from a supplied map, except those having a specified key. |
map:for-each |
Applies a supplied function to every entry in a map, returning the concatenation of the results. |
Determines whether two atomic values can coexist as separate keys within a map.
op:same-key
($k1
as
xs:anyAtomicType
, $k2
as
xs:anyAtomicType
) as
xs:boolean
This function is ·deterministic·, ·context-independent·, and ·focus-independent·.
The internal function op:same-key
(which is not available at the user level) is used to assess whether two atomic
values are considered to be duplicates when used as keys in a map. A map cannot
contain two separate entries whose keys are the same as defined by this function.
The function is also used when matching keys in functions such as map:get
and map:remove
.
The function returns true if and only if one of the following conditions is true:
All of the following conditions are true:
$k1
is an instance of xs:string
, xs:anyURI
, or xs:untypedAtomic
$k2
is an instance of xs:string
, xs:anyURI
, or xs:untypedAtomic
fn:codepoint-equal($k1, $k2)
Note:
Strings are compared without any dependency on collations.
All of the following conditions are true:
$k1
is an instance of xs:decimal
, xs:double
, or xs:float
$k2
is an instance of xs:decimal
, xs:double
, or xs:float
One of the following conditions is true:
Both $k1
and $k2
are NaN
Note:
xs:double('NaN')
is the same key as xs:float('NaN')
Both $k1
and $k2
are positive infinity
Note:
xs:double('INF')
is the same key as xs:float('INF')
Both $k1
and $k2
are negative infinity
Note:
xs:double('-INF')
is the same key as xs:float('-INF')
$k1
and $k2
when converted to decimal numbers with no rounding or loss of precision
are mathematically equal.
Note:
Every instance of xs:double
, xs:float
, and xs:decimal
can be represented
exactly as a decimal number provided enough digits are available both before and after
the decimal point. Unlike the eq
relation, which converts both operands to xs:double
values, possibly losing precision in the process, this
comparison is transitive.
Note:
Positive and negative zero are the same key.
All of the following conditions are true:
$k1
is an instance of xs:date
, xs:time
, xs:dateTime
,
xs:gYear
, xs:gYearMonth
, xs:gMonth
, xs:gMonthDay
, or xs:gDay
$k2
is an instance of xs:date
, xs:time
, xs:dateTime
,
xs:gYear
, xs:gYearMonth
, xs:gMonth
, xs:gMonthDay
, or xs:gDay
One of the following conditions is true:
Both $k1
and $k2
have a timezone
Neither $k1
nor $k2
has a timezone
fn:deep-equal($k1, $k2)
Note:
The use of deep-equal
rather than eq
ensures that comparing values of different
types yields false
rather than an error.
Note:
Unlike the eq
operator, this comparison has no dependency on the implicit timezone, which means
that
the question of whether or not a map contains duplicate keys is not dependent on this
aspect of the dynamic context.
All of the following conditions are true:
$k1
is an instance of xs:boolean
, xs:hexBinary
, xs:base64Binary
,
xs:duration
, xs:QName
, or xs:NOTATION
$k2
is an instance of xs:boolean
, xs:hexBinary
, xs:base64Binary
,
xs:duration
, xs:QName
, or xs:NOTATION
fn:deep-equal($k1, $k2)
Note:
The use of deep-equal
rather than eq
ensures that comparing values of different
types yields false
rather than an error.
The rules for comparing keys in a map are chosen to ensure that the comparison is:
Context-free: there is no dependency on the static or dynamic context
Error-free: any two atomic values can be compared, and the result is either true or false, never an error
Transitive: if A is the same key as B, and B is the same key as C, then A is the same key as C.
As always, any algorithm that delivers the right result is acceptable. For example,
when testing whether an xs:double
value D is the same key as an xs:decimal
value that has N significant digits, it is not
necessary to know all the digits in the decimal expansion of D to establish the result: computing the first N+1
significant digits (or indeed, simply knowing that there are more than N significant digits) is sufficient.
Returns a map that combines the entries from a number of existing maps.
map:merge
($maps
as
map(*)*
) as
map(*)
map:merge
($maps
as
map(*)*
, $options
as
map(*)
) as
map(*)
This function is ·deterministic·, ·context-independent·, and ·focus-independent·.
The function map:merge
returns a map that
is formed by combining the contents of the maps supplied in the $maps
argument.
Informally, the supplied maps are combined as follows:
There is one entry in the returned map for each distinct key present in the union of the input maps, where two keys are distinct if they are not the ·same key·.
If there are duplicate keys, that is, if two or more maps contain entries having the
·same key·, then the way this is handled is
controlled by the second ($options
) argument.
The definitive specification is as follows.
The effect of calling the single-argument function is the same as the effect of
calling the two-argument function with an empty map as the value of $options
.
The $options
argument can be used to control the way in which duplicate keys are handled.
The ·option parameter conventions· apply.
The entries that may appear in the $options
map are as follows:
| Key | Value | Meaning |
|---|---|---|
duplicates |
Determines the policy for handling duplicate keys: specifically, the action to be
taken if two maps in the input sequence $maps contain entries with key values
K1 and K2 where K1 and K2 are the
·same key·.
|
|
reject |
An error is raised [err:FOJS0003] if duplicate keys are encountered. | |
use-first |
If duplicate keys are present, all but the first of a set of duplicates are ignored,
where the ordering is based on the order of maps in the $maps argument.
|
|
use-last |
If duplicate keys are present, all but the last of a set of duplicates are ignored,
where the ordering is based on the order of maps in the $maps argument.
|
|
use-any |
If duplicate keys are present, all but one of a set of duplicates are ignored, and it is ·implementation-dependent· which one is retained. | |
combine |
If duplicate keys are present, the result map includes an entry for the key whose
associated value is the sequence-concatenation of all the values associated with the
key,
retaining order based on the order of maps in the $maps argument.
The key value in the result map that corresponds to such a set of duplicates must
be the ·same key· as each of the duplicates, but it is
otherwise unconstrained: for example if the duplicate keys are xs:byte(1)
and xs:short(1) , the key in the result could legitimately be xs:long(1) .
|
The result of the function call map:merge($MAPS, $OPTIONS)
is defined to be consistent with the result of the expression:
let $FOJS0003 := QName("http://www.w3.org/2005/xqt-errors", "FOJS0003"), $duplicates-handler := map { "use-first": function($a, $b) {$a}, "use-last": function($a, $b) {$b}, "combine": function($a, $b) {$a, $b}, "reject": function($a, $b) {fn:error($FOJS0003)}, "use-any": function($a, $b) {fn:random-number-generator()?permute(($a, $b))[1]} }, $combine-maps := function($A as map(*), $B as map(*), $deduplicator as function(*)) { fn:fold-left(map:keys($B), $A, function($z, $k){ if (map:contains($z, $k)) then map:put($z, $k, $deduplicator($z($k), $B($k))) else map:put($z, $k, $B($k)) }) } return fn:fold-left($MAPS, map{}, $combine-maps(?, ?, $duplicates-handler(($OPTIONS?duplicates, "use-first")[1]))
Note:
By way of explanation, $combine-maps
is a function that combines
two maps by iterating over the keys of the second map, adding each key and its corresponding
value to the first map as it proceeds. The second call of fn:fold-left
in the return
clause then iterates over the maps supplied in the call
to map:merge
, accumulating a single map that absorbs successive maps
in the input sequence by calling $combine-maps
.
This algorithm processes the supplied maps in a defined order, but processes the keys within each map in implementation-dependent order.
The use of fn:random-number-generator
represents one possible conformant
implementation for "duplicates":"use-any"
, but it is not the only conformant
implementation and is not intended to be a realistic implementation. The purpose of
this
option is to allow the implementation to use whatever strategy is most efficient;
for example,
if the input maps are processed in parallel, then specifying "duplicates":"use-any"
means that the implementation does not need to keep track of the original order of
the sequence of input
maps.
An error is raised [err:FOJS0003] if the value of
$options
indicates that duplicates are to be rejected, and a duplicate key is encountered.
An error is raised [err:FOJS0005] if the value of
$options
includes an entry whose key is defined
in this specification, and whose value is not a permitted value for that key.
If the input is an empty sequence, the result is an empty map.
If the input is a sequence of length one, the result map is indistinguishable from the supplied map.
There is no requirement that the supplied input maps should have the same or compatible
types. The type of a map (for example map(xs:integer, xs:string)
) is
descriptive of the entries it currently contains, but is not a constraint on how the
map
may be combined with other maps.
let $week := map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", 5:"Freitag", 6:"Samstag"}
The expression map:merge(())
returns map{}
. (Returns an empty map).
The expression map:merge((map:entry(0, "no"), map:entry(1, "yes")))
returns map{0:"no", 1:"yes"}
. (Returns a map with two entries).
The expression map:merge(($week, map{7:"Unbekannt"}))
returns map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag",
5:"Freitag", 6:"Samstag", 7:"Unbekannt"}
. (The value of the existing map is unchanged; the returned map
contains all the entries from $week
, supplemented with an additional
entry.)
The expression map:merge(($week, map{6:"Sonnabend"}), map{"duplicates":"use-last"})
returns map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag",
5:"Freitag", 6:"Sonnabend"}
. (The value of the existing map is unchanged; the returned map
contains all the entries from $week
, with one entry replaced by a
new entry. Both input maps contain an entry with the key 6
; the
one used in the result is the one that comes last in the input
sequence.)
The expression map:merge(($week, map{6:"Sonnabend"}), map{"duplicates":"use-first"})
returns map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag",
5:"Freitag", 6:"Samstag"}
. (The value of the existing map is unchanged; the returned map
contains all the entries from $week
, with one entry replaced by a
new entry. Both input maps contain an entry with the key 6
; the
one used in the result is the one that comes first in the input
sequence.)
The expression map:merge(($week, map{6:"Sonnabend"}), map{"duplicates":"combine"})
returns map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag",
5:"Freitag", 6:("Samstag", "Sonnabend")}
. (The value of the existing map is unchanged; the returned map
contains all the entries from $week
, with one entry replaced by a
new entry. Both input maps contain an entry with the key 6
; the
entry that appears in the result is the sequence-concatenation of the entries
in the input maps, retaining order.)
Returns the number of entries in the supplied map.
map:size
($map
as
map(*)
) as
xs:integer
This function is ·deterministic·, ·context-independent·, and ·focus-independent·.
The function map:size
takes any ·map·
as its $map
argument and returns the number of entries that are present
in the map.
The expression map:size(map{})
returns 0
.
The expression map:size(map{"true":1, "false":0})
returns 2
.
Returns a sequence containing all the keys present in a map
map:keys
($map
as
map(*)
) as
xs:anyAtomicType*
This function is ·nondeterministic-wrt-ordering·, ·context-independent·, and ·focus-independent·.
The function map:keys
takes any ·map·
as its $map
argument and returns the keys that are present in the map as
a sequence of atomic values, in ·implementation-dependent· order.
The function is non-deterministic with respect to ordering (see 1.7.4 Properties of functions). This means that two calls with the same argument are not guaranteed to produce the results in the same order.
The number of items in the result will be the same as the number of entries in the map, and the result sequence will contain no duplicate values.
The expression map:keys(map{1:"yes", 2:"no"})
returns some permutation of (1,2)
. (The result is in ·implementation-dependent· order.)
Tests whether a supplied map contains an entry for a given key
map:contains
($map
as
map(*)
, $key
as
xs:anyAtomicType
) as
xs:boolean
This function is ·deterministic·, ·context-independent·, and ·focus-independent·.
The function map:contains
returns true if the ·map· supplied as $map
contains an entry with the ·same key· as the
supplied value of $key
; otherwise it returns false.
let $week := map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", 5:"Freitag", 6:"Samstag"}
The expression map:contains($week, 2)
returns true()
.
The expression map:contains($week, 9)
returns false()
.
The expression map:contains(map{}, "xyz")
returns false()
.
The expression map:contains(map{"xyz":23}, "xyz")
returns true()
.
The expression map:contains(map{"abc":23, "xyz":()}, "xyz")
returns true()
.
Returns the value associated with a supplied key in a given map.
map:get
($map
as
map(*)
, $key
as
xs:anyAtomicType
) as
item()*
This function is ·deterministic·, ·context-independent·, and ·focus-independent·.
The function map:get
attempts to find an entry within the ·map· supplied as $map
that has the ·same key· as the supplied
value of $key
. If there is such an entry, it returns the associated value;
otherwise it returns an empty sequence.
A return value of ()
from map:get
could indicate that
the key is present in the map with an associated value of ()
, or it could
indicate that the key is not present in the map. The two cases can be distinguished
by
calling map:contains
.
Invoking the ·map· as a function item has the same effect
as calling get
: that is, when $map
is a map, the expression
$map($K)
is equivalent to map:get($map, $K)
. Similarly, the
expression map:get(map:get(map:get($map, 'employee'), 'name'), 'first')
can
be written as $map('employee')('name')('first')
.
let $week := map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", 5:"Freitag", 6:"Samstag"}
The expression map:get($week, 4)
returns "Donnerstag"
.
The expression map:get($week, 9)
returns ()
. (When the key is not present, the function returns an empty
sequence.)
The expression map:get(map:entry(7,()), 7)
returns ()
. (An empty sequence as the result can also signify that the key is
present and the associated value is an empty sequence.)
Searches the supplied input sequence and any contained maps and arrays for a map entry with the supplied key, and returns the corresponding values.
map:find
($input
as
item()*
, $key
as
xs:anyAtomicType
) as
array(*)
This function is ·deterministic·, ·context-independent·, and ·focus-independent·.
The function map:find
searches the sequence supplied as $input
looking for map entries whose key is the ·same key·
as $key
. The associated value in any such map entry (each being in general a sequence)
is returned as a member of the result array.
The search processes the $input
sequence using the following recursively-defined rules
(any equivalent algorithm may be used provided it delivers
the same result, respecting those rules that constrain the order of the result):
To process a sequence, process each of its items in order.
To process an item that is an array, process each of the array's members in order (each member is, in general, a sequence).
To process an item that is a map, then for each key-value entry (K, V) in the map (in ·implementation-dependent· order) perform both of the following steps, in order:
If K is the ·same key· as $key
,
then add V as a new member to the end of the result array.
Process V (which is, in general, a sequence).
To process an item that is neither a map nor an array, do nothing. (Such items are ignored).
If $input
is an empty sequence, map, or array, or if the requested $key
is not found,
the result will be a zero-length array.
let $responses := [map{0:'no', 1:'yes'}, map{0:'non', 1:'oui'}, map{0:'nein', 1:('ja', 'doch')}]
The expression map:find($responses, 0)
returns ['no', 'non', 'nein']
.
The expression map:find($responses, 1)
returns ['yes', 'oui', ('ja', 'doch')]
.
The expression map:find($responses, 2)
returns []
.
let $inventory := map{"name":"car", "id":"QZ123", "parts": [map{"name":"engine", "id":"YW678", "parts":[]}]}
The expression map:find($inventory, "parts")
returns [[map{"name":"engine", "id":"YW678", "parts":[]}], []]
.
Returns a map containing all the contents of the supplied map, but with an additional entry, which replaces any existing entry for the same key.
map:put
($map
as
map(*)
, $key
as
xs:anyAtomicType
, $value
as
item()*
) as
map(*)
This function is ·deterministic·, ·context-independent·, and ·focus-independent·.
The function map:put
returns a ·map· that contains all entries from the supplied $map
,