Name

[2.0] exactly-one()

Raises an error unless its argument is a singleton, a sequence containing exactly one item. Be aware that exactly-one() terminates processing. For a more flexible approach, use the count() function to determine the cardinality of a sequence.

Syntax

item()+ exactly-one(item()*)

Inputs

A sequence.

Outputs

If the input sequence contains exactly one item, the input sequence is returned. Otherwise, exactly-one() raises an error.

Defined in

XQuery 1.0 and XPath 2.0 Functions and Operators section 15.2, “Functions That Test the Cardinality of Sequences.” More details about this function can be found in XQuery 1.0 and XPath 2.0 Formal Semantics section 7.2, “Standard Functions with Specific Static Typing Rules.”

Example

The exactly-one() function is useful for working with XSLT 2.0’s static typing. Any sequence can be empty, a singleton, or have multiple items. If we need to test the cardinality of the sequence at runtime, the exactly-one() function can enforce the restriction that a sequence must be a singleton. However, exactly-one() terminates stylesheet processing if its argument doesn’t have exactly one item, so it’s far more flexible to use the count() function to check the number of items in a sequence before working with it.

Here is a short stylesheet that invokes the exactly-one() function with a singleton:

<?xml version="1.0"?>
<!-- exactly-one.xsl --> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.