Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT 3.0 Dynamic select with variable in apply-templates?

Tags:

xslt

I want to apply templates to a set of nodes where part of the select path is a variable. I'm using Saxon-HE 9.8 (awesome lib!)

I'm trying to achieve the following

<variable name="x" select="string('baz')"/>
<xsl:apply-templates select="foo/bar/$x"/>

This doesn't seem to work. Is there a syntax that will allow me to dynamically construct the select XPath for this apply-templates instruction? Or, is there another technique for dynamically achieving this effect? I even tried pushing this down to my <xsl:template match=foo/bar/$x> but no luck.

My motivation here is in my application the variable value is coming from a separate configuration file. Based on the configuration I need to run templates matching specific path segments driven by config strings...

like image 598
shawn Avatar asked Oct 12 '25 22:10

shawn


1 Answers

If your variables are always going to be a simple string value expressing the name of an element, then one option would be to match a little more generically on an element and then use the string variable in a predicate to filter for a match of the element name:

<xsl:apply-templates select="foo/bar/*[local-name() = $x]"/>

With Saxon-PE or Saxon-EE, you could leverage xsl:evaluate and do something like this:

<xsl:variable name="var" as="node()*">
  <xsl:evaluate xpath="concat('foo/bar/',$x)" context-item="."/>
</xsl:variable>
<xsl:apply-templates select="$var"/>
like image 99
Mads Hansen Avatar answered Oct 16 '25 12:10

Mads Hansen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!