Sponsored

XSLT Reference

map:merge()

XSLT 3.0 map function

Merges multiple maps into one, with duplicate key handling controlled by an options map.

Syntax
map:merge(maps, options?)

Description

map:merge() combines a sequence of maps into a single map. When two or more maps share the same key, the behavior is controlled by the duplicates option. The function is immutable — the input maps are not modified; a new map is returned.

The duplicates option accepts: "reject" (error), "use-first", "use-last" (default), "combine" (values become a sequence), or "unspecified".

Parameters

ParameterTypeRequiredDescription
mapsmap()YesA sequence of maps to merge.
optionsmap(xs:string, item())?NoOptions map; key "duplicates" controls duplicate handling.

Return value

map(*) — a new map containing all entries from the input maps.

Examples

Merging two maps with use-last (default)

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="defaults" select="map{'color':'blue', 'size':'medium', 'weight':1}"/>
    <xsl:variable name="overrides" select="map{'color':'red', 'weight':5}"/>
    <xsl:variable name="merged" select="map:merge(($defaults, $overrides))"/>
    <config>
      <color><xsl:value-of select="map:get($merged, 'color')"/></color>
      <size><xsl:value-of select="map:get($merged, 'size')"/></size>
      <weight><xsl:value-of select="map:get($merged, 'weight')"/></weight>
    </config>
  </xsl:template>
</xsl:stylesheet>

Output:

<config>
  <color>red</color>
  <size>medium</size>
  <weight>5</weight>
</config>

Merging with combine to accumulate duplicate values

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="m1" select="map{'tag':'xslt', 'tag2':'xml'}"/>
    <xsl:variable name="m2" select="map{'tag':'xpath'}"/>
    <xsl:variable name="merged" select="map:merge(($m1, $m2),
      map{'duplicates':'combine'})"/>
    <tags>
      <xsl:for-each select="map:get($merged, 'tag')">
        <tag><xsl:value-of select="."/></tag>
      </xsl:for-each>
    </tags>
  </xsl:template>
</xsl:stylesheet>

Output:

<tags>
  <tag>xslt</tag>
  <tag>xpath</tag>
</tags>

Notes

  • The default duplicate behavior (use-last) means later maps in the input sequence win.
  • "reject" causes err:FOJS0003 when a duplicate key is encountered.
  • map:merge() also accepts an empty sequence, returning an empty map.
  • Maps are immutable in XDM; merge always produces a new map.

See also