xslt-3.0

is it possible to match (apply-templates) on maps and array?


Its quite common for me to use a pipeline pattern where I take an input (lets assume xml) and transform it through a series of transformations into an output before returning it from the stylesheet.

These intermediary transforms most commonly use 'apply-templates' to 'map' (like a functor) the input to some new structure.

But if I map some input into a map/array structure (doesnt need to be JSON) I can't see of a way to then apply-templates to it in the same way.

(my suspicion is it isnt directly supported)


Solution

  • In XSLT 3, you can certainly write match patterns for maps and arrays e.g.

    <xsl:template match=".[. instance of map(*)]">
    

    and

    <xsl:template match=".[. instance of array(*)]">
    

    are the most generic matches; you can also use more specific matches like match=".[. instance of map(xs:string, xs:string)]".

    XSLT/XPath 4 is on its way to introduce some more compact and comprehensive type expressions and patterns for maps and arrays (https://qt4cg.org/specifications/xslt-40/Overview-diff.html#pattern-examples, https://qt4cg.org/specifications/xslt-40/Overview-diff.html#type-patterns).

    In the current version of XSLT 3 with XPath 3.1 you can of course write patterns like

    <xsl:template match=".[. instance of map(*)][?foo = 'bar']">
    

    Online sample.