View Old View New View Both View Only Previous Next

This draft contains only sections that have differences from the version that it modified.

W3C

XPath and XQuery Functions and Operators 4.0

W3C Editor's Draft 23 February 2026

This version:
https://qt4cg.org/specifications/xpath-functions-40/
Latest version of XPath and XQuery Functions and Operators 4.0:
https://qt4cg.org/specifications/xpath-functions-40/
Most recent Recommendation of XPath and XQuery Functions and Operators:
https://www.w3.org/TR/2017/REC-xpath-functions-31-20170321/
Editor:
Michael Kay, Saxonica <http://www.saxonica.com/>

This document is also available in these non-normative formats: Specification in XML format and XML function catalog.


Abstract

This document defines constructor functions, operators, and functions on the datatypes defined in [XML Schema Part 2: Datatypes Second Edition] and the datatypes defined in [XQuery and XPath Data Model (XDM) 4.0]. It also defines functions and operators on nodes and node sequences as defined in the [XQuery and XPath Data Model (XDM) 4.0]. These functions and operators are defined for use in [XML Path Language (XPath) 4.0] and [XQuery 4.0: An XML Query Language] and [XSL Transformations (XSLT) Version 4.0] and other related XML standards. The signatures and summaries of functions defined in this document are available at: http://www.w3.org/2005/xpath-functions/.

A summary of changes since version 3.1 is provided at H Changes since 3.1.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document.

This document is a working draft developed and maintained by a W3C Community Group, the XQuery and XSLT Extensions Community Group unofficially known as QT4CG (where "QT" denotes Query and Transformation). This draft is work in progress and should not be considered either stable or complete. Standard W3C copyright and patent conditions apply.

The community group welcomes comments on the specification. Comments are best submitted as issues on the group's GitHub repository.

The community group maintains two extensive test suites, one oriented to XQuery and XPath, the other to XSLT. These can be found at qt4tests and xslt40-test respectively. New tests, or suggestions for correcting existing tests, are welcome. The test suites include extensive metadata describing the conditions for applicability of each test case as well as the expected results. They do not include any test drivers for executing the tests: each implementation is expected to provide its own test driver.

Dedication

The publications of this community group are dedicated to our co-chair, Michael Sperberg-McQueen (1954–2024).


17 External resources and data formats

These functions in this section access resources external to a query or stylesheet, and convert between external file formats and their XPath and XQuery data model representation.

17.2 Functions on XML Data

These functions convert between the lexical representation of XML and the tree representation.

(The fn:serialize function also handles HTML and JSON output, but is included in this section for editorial convenience.)

FunctionMeaning
fn:parse-xmlThis function takes as input an XML document, and returns the document node at the root of an XDM tree representing the parsed document.
fn:parse-xml-fragmentThis 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:serializeThis function serializes the supplied input sequence $input as described in [XSLT and XQuery Serialization 3.1], returning the serialized representation of the sequence as a string.
fn:xsd-validatorGiven an XSD schema, delivers a function item that can be invoked to validate a document or element node against this schema.

17.2.5 fn:xsd-validator

Changes in 4.0  

  1. New in 4.0

Summary

Given an XSD schema, delivers a function item that can be invoked to validate a document or element node against this schema.

Signature
fn:xsd-validator(
$optionsas map(*)?:= {}
) as function((document-node(*) | element(*) | attribute(*))?) as record(is-valid as xs:boolean, typed-node? as node(), error-details? as record(*)*)
Properties

This function is deterministic, context-dependent, and focus-independent.

Rules

The fn:xsd-validator function returns a function item that can be used to validate a document node or an element node with respect to a supplied schema.

The details of how the schema is assembled, and the way it is used, are defined by the supplied $options. If the $options argument is absent or empty the effect is to use the schema components from the static context of the call on fn:xsd-validator. In the general case, however, the schema used for validation may include components from any or all of the following:

  • The static context of the function call

  • Explicitly supplied schema documents

  • Schema components referenced in xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes within the instance document being validated.

More details of schema assembly appear below. Taken together, the assembled components must constitute a valid schema.

The function is designed to separate the process of assembling a schema from the process of performing instance validation. However, if the schema is to include components identified in xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, then the process of assembling the schema cannot be completed until the instance document is available.

The options recognized are as follows. The option parameter conventions apply.

record(
trusted?as xs:boolean,
use-imported-schema?as xs:boolean,
schema?as element(xs:schema)*,
target-namespace?as xs:anyURI*,
schema-location?as xs:anyURI*,
use-xsi-schema-location?as xs:boolean,
xsd-version?as xs:decimal,
validation-mode?as xs:string,
type?as xs:QName?,
return-typed-node?as xs:boolean,
return-error-details?as xs:boolean
)
KeyValueMeaning

trusted?

Indicates whether the validation process may cause external resources to be fetched (including, for example, documents referenced using the schema-location property, or xsi:schemaLocation attributes within the document being validated).
  • Type: xs:boolean

  • Default: false()

trueThe validation process may retrieve external resources.
falseThe validation process must not retrieve any external resources unless access to these resources has been explicitly enabled.

use-imported-schema?

If true, the schema to be used for validation includes the schema components available in the static context of the function call. If false, these components are not used.
  • Type: xs:boolean

  • Default: true

schema?

A list of XDM nodes containing XSD schema documents to be used for validation.
  • Type: element(xs:schema)*

  • Default: ()

target-namespace?

A list of target namespaces identifying schema components to be used for validation. The way in which the processor locates schema components for the specified target namespaces is implementation-defined. A zero-length string denotes a no-namespace schema.
  • Type: xs:anyURI*

  • Default: ()

schema-location?

A list of locations of XSD schema documents to be used to assemble a schema. Any relative URIs are resolved relative to the base URI of the function call. Access to the schema documents at these locations is allowed regardless of the value of the trusted option; access to indirectly referenced schema documents (for example, using xs:include is allowed only if the trusted option is set to true.
  • Type: xs:anyURI*

  • Default: ()

use-xsi-schema-location?

If true, the schema to be used for validation includes any schema documents referenced by xsi:schemaLocation or xsi:noNamespaceSchemaLocation attributes in the instance document being validated. If false, these attributes are ignored.
  • Type: xs:boolean

  • Default: false

xsd-version?

Set to the decimal value 1.0 or 1.1 to indicate which version of XSD is to be used. The default is implementation-defined. A processor may use a later version of XSD than the version requested, but must not use an earlier version.
  • Type: xs:decimal

validation-mode?

The validation mode.
  • Type: xs:string

strictValidates the input using the element or attribute declaration for the operand node. This element or attribute declaration must exist. This is the default when the type option is absent.
laxValidates the input using the element or attribute declaration for the operand node, if it exists.
by-typeValidates the input using the supplied governing type. This is the default when the type option is present.

type?

Establishes the governing type for validation. The type must be present in the assembled schema.
  • Type: xs:QName?

return-typed-node?

If true, the result of the generated validation function, when validation is successful, includes the property typed-node which contains a copy of the target node augmented with type annotations and expanded default values. If false, the typed node is not included in the result. If a node containing type annotations is to be returned, then the schema used for validation must be compatible with all other schemas used within the same query or stylesheet, as described in [XQuery and XPath Data Model (XDM) 4.0] section 4.1.2 Schema Consistency; this is to ensure that the type annotations in the validated document have a consistent interpretation.
  • Type: xs:boolean

  • Default: true

return-error-details?

If true, the result of the generated validation function, when validation is unsuccessful, includes detailed information about the nature of the validity errors that were found. If false, the result only includes an indication that the document was invalid. Note that setting the value to false means that validation can complete as soon as the first error is found.
  • Type: xs:boolean

  • Default: false

The first task of the function is to assemble a schema (that is, a collection of schema components). Schema components can come from a number of sources, and a schema can be assembled from more than one source, provided that the total collection of components comprises a valid schema: the main thing that will prevent this is if two sources contain conflicting definitions of the same named component.

  • The default is to use the in-scope schema components from the static context of the function call.

  • Instead, or in addition, schema components may be loaded explictly for this validator. Supplementary schema components may be requested in a number of ways:

    • The schema-location option can specify one or more URIs that are interpreted as locations for source XSD schema documents, which are then assembled into a schema as described in the XSD specifications.

    • The schema option can be used to identify one or more xs:schema element nodes holding source schema documents. This allows a schema to be constructed dynamically by the application, or to be held as a global variable in the source code of a query or stylesheet module.

    • The target-namespace option can be used to supply the target namespaces of additional schema components that are known to the system or that are made available using some external mechanism. For example, the system might have built-in schemas for common namespaces such as the xml, fn, or xlink namespaces, or it might have a mechanism allowing schemas for a particular namespace to be registered using an external API or configuration mechanism.

  • The use-xsi-schema-location also allows the application to request that schema documents referenced from xsi:schemaLocation or xsi:noNamespaceSchemaLocation attributes should be included in the schema. By default these attributes are ignored.

  • It is acceptable to assemble a schema from more than one of these sources. In addition, any of these sources can bring in additional components by the use of the XSD directives xsl:include and xsl:import. The important constraint is that the result should be a valid schema. This will only be the case if the sources used to assemble the schema are compatibleDM with each other: see [XQuery and XPath Data Model (XDM) 4.0] section 4.1.2 Schema Consistency.

  • The XSD specification allows a schema to be used for validation even when it contains unresolved references to absent schema components. It is implementation-defined whether this function allows the schema to be incomplete in this way. For example, some processors might allow validation using a schema in which an element declaration contains a reference to a type declaration that is not present in the schema, provided that the element declaration is never needed in the course of a particular validation episodes.

Having assembled a schema, the next task is to validate a supplied node (and the subtree rooted at that node).

Note:

This description is a deliberate simplification. If the use-xsi-schema-location option is true, then assembly of the schema is not completed until the instance document is available, and in practice overlaps with the validation process.

The xsd-validator function returns a function item (call it V) with the following characteristics:

  • V has an arity of one. Call the value of the supplied argument $target. The required type of $target is (document-node(*) | element(*) | attribute(*))?: that is, it accepts either a well-formed document node, or an element node, or an attribute node, or an empty sequence.

  • If the argument is an empty sequence then the result of V is also an empty sequence.

  • In other cases, the result of a call on V is a record containing the following fields:

    • is-valid as xs:boolean. This field is always present, and indicates whether the supplied $target node was found to be valid against the schema. The value is true if either (a) the validation outcome was valid, or (b) lax validation was requested and the validation outcome was notKnown. In other cases it is false.

    • typed-node as (document-node(*) | element(*) | attribute(*)). This field is present only when (a) the option return-typed-node was set (explicitly or implicitly) to true, and (b) the value of the is-valid field is true. It represents the root of a tree that is a deep copy of the input tree, augmented with type annotations and default values.

    • error-details as map(*)*. This field is present only when (a) the option return-error-details was set to true, and (b) the supplied document was found to be invalid. The value is a sequence of maps, each containing details of one invalidity that was found. The precise details of the invalidities are implementation-defined, but they may include the following fields, if the information is available:

      • message. A string containing the text of an error message, intended for a human reader.

      • rule. A reference to the rule in the XSD specification that was violated. This is a string comprising four parts separated by the character U+007C (VERTICAL BAR, |) :

        • "1.0" or "1.1" indicating whether the reference is to the XSD 1.0 or 1.1 specification.

        • "1" or "2" indicating whether the reference is to part 1 or part 2 of the specification.

        • The name of the validation rule (for example "Datatype Valid").

        • The clause number within that validation rule (for example "2.3").

        For example, if an attribute is declared to be of type xs:integer, but the actual value is not in the lexical space of xs:integer, the value of rule might be "1.1|2|Datatype Valid|2.1".

      • node. The node that was found to be invalid. Note that when a containing element C is invalid because a child element D is not allowed by its content model, the invalid node is C, not D.

      • error-node. The node whose presence led to detection of the invalidity. In the above example, this would be D.

      • error-uri. The URI of the XML entity in which the error was detected.

      • line-number. The line number where the error was detected, within its external entity.

      • column-number. The column number where the error was detected, within the error line number.

  • The validation is performed as described in 17.2.4 XSD validation, with the assembled schema as the effective schema and $target as the operand node.

  • If the use-xsi-schema-location option is true and a failure occurs processing an xsi:schemaLocation or xsi:noNamespaceSchemaLocation attribute (for example, because a schema document cannot be retrieved, or because the referenced schema document is invalid, or because it is incompatible with other schema components) this is treated as an invalidity, not as a dynamic error: V returns successfully with is-valid set to false.

  • The function V may fail with a dynamic error if it is not possible to determine whether or not the instance document is valid. This may happen, for example, if processor-defined limits are exceeded.

Error Conditions

A dynamic error is raised [err:FODC0009] if the processor is not schema-aware, or if no schema processor with the required capabilities (such as XSD 1.1 support) is available.

A dynamic error is raised [err:FODC0015] if it is not possible to assemble a valid and consistent schema.

Notes

Both XQuery and XSLT provide capabilities for XSD-based schema validation in earlier versions of the specifications, and those are retained in 4.0. This function provides additional capability:

  • It is possible to control validation more precisely, through a wider range of options;

  • It is possible to validate different instance documents against different schemas;

  • Information about any invalidities is made available to the application, rather than simply causing a dynamic error;

  • The capability is provided by means of a function rather than custom syntax, making it easier to integrate into an application.

  • The capability is available through XPath alone, and therefore with host languages other than XQuery and XSLT.

Three possible ways of using the function include:

  • To simply test whether or not a document is valid against a schema, set the options return-typed-node and return-error-details to false, and simply test the value of the is-valid field returned when the validation function is called.

  • To obtain a typed XDM tree from an input document that is expected to be valid, set the option return-typed-node to true. On return from the validation function, test the value of the is-valid field; call fn:error if the value is false; otherwise use the typed-node property of the result. The main benefit of using a typed XDM tree is that it allows static type checking of path expressions: this benefit only applies when the schema used for validation is the imported schema used in the static context. However, there are cases where validation against a different schema is appropriate, for example when validating the result of one query or transformation that is to be used as input to another.

  • To validate an input document and provide feedback to the document author about any validity problems that were found, set return-error-details to true. If the result of the validation function has is-valid = false(), process the returned error-details. The information available for this part of the processing may not be 100% interoperable, though with care it should be possible to write the query in such a way that it works with different processors.

The validation process is explained in more detail in the XQuery ([XQuery 4.0: An XML Query Language] section 4.25 Validate Expressions) and XSLT ([XSL Transformations (XSLT) Version 4.0] section 25.4 Validation) specifications.

The function has no effect on the static context. Schemas loaded using this function, either directly or via the effect of xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, are not added to the static context and have no effect on any other validation episodes. A processor may cache schema components to reduce the cost of processing the same schema repeatedly, but this has no observable effect other than on performance.

Examples
Expression:
let $schema := 
  <xs:schema>
    <xs:element name="distance" type="xs:decimal"/>
  </xs:schema>
let $validator := xsd-validator({'schema': $schema})
return ($validator(<distance>8.5</distance>)?is-valid,
        $validator(<distance>8.5km</distance>)?is-valid)
Result:
true(), false()
Expression:
let $schema := 
  <xs:schema>
    <xs:element name="distance" type="xs:decimal"/>
  </xs:schema>
let $validator := xsd-validator({'schema': $schema})
let $typed-result := $validator(<distance>8.5</distance>)?typed-node
return $typed-result instance of element(distance, xs:decimal)
Result:
true()