Sponsored

XSLT Reference

map:keys()

XSLT 3.0 map function

Returns all keys of a map as a sequence of atomic values in implementation-defined order.

Syntax
map:keys(map)

Description

map:keys() returns a sequence containing all the keys present in a map. The order of keys in the result is implementation-defined and should not be relied upon. Keys are always atomic values (xs:anyAtomicType). For an empty map, the empty sequence is returned.

Parameters

ParameterTypeRequiredDescription
mapmap(*)YesThe map whose keys are to be returned.

Return value

xs:anyAtomicType* — a sequence of all keys in the map; empty sequence for an empty map.

Examples

Iterating over all map keys

Stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:map="http://www.w3.org/2005/xpath-functions/map">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <xsl:variable name="scores" select="map{
      'Alice': 95,
      'Bob': 82,
      'Carol': 91
    }"/>
    <report>
      <xsl:for-each select="sort(map:keys($scores))">
        <student name="{.}" score="{map:get($scores, .)}"/>
      </xsl:for-each>
    </report>
  </xsl:template>
</xsl:stylesheet>

Output:

<report>
  <student name="Alice" score="95"/>
  <student name="Bob" score="82"/>
  <student name="Carol" score="91"/>
</report>

Converting a map to XML elements

Stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:map="http://www.w3.org/2005/xpath-functions/map">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <xsl:variable name="config" select="map{
      'theme': 'dark',
      'lang': 'en',
      'version': '3.0'
    }"/>
    <config>
      <xsl:for-each select="sort(map:keys($config))">
        <xsl:element name="{.}">
          <xsl:value-of select="map:get($config, .)"/>
        </xsl:element>
      </xsl:for-each>
    </config>
  </xsl:template>
</xsl:stylesheet>

Output:

<config>
  <lang>en</lang>
  <theme>dark</theme>
  <version>3.0</version>
</config>

Notes

  • The order of keys is not guaranteed; wrap with sort() for deterministic output.
  • Keys can be any atomic type: xs:string, xs:integer, xs:date, etc.
  • Duplicate keys cannot exist in a map, so count(map:keys($m)) always equals map:size($m).

See also