HYMXDEV
HYMXDEV

Reputation: 443

XSLT dynamic xpath child selection

I need to select childs recursively by a given path. This is my XML structure:

<items>
   <item name="first">
      <item name="fist-first">
         [...]
      </item>
      <item name="first-second">
         [...]
      </item>
      [...]
   </item>
</items>

I need to select a specific item by path (like "0-1" to select the second child of the first element) passed by xsl:param. I have a string representing the actual node path concerning their child position.

Does anybody know if this is possible and give me some help?

I use saxon 9.8he.

Thanks in advance

Upvotes: 0

Views: 269

Answers (2)

Michael Kay
Michael Kay

Reputation: 163655

First turn $path into a sequence of positive integers, such as (1,4,6), using the tokenize() function, and then call this recursive function:

<xsl:function name="f:by-path" as="element()?">
 <xsl:param name="origin" as="element()*"/>
 <xsl:param name="path" as="xs:integer*"/>
 <xsl:sequence select="
     if (empty($path)) 
     then $origin 
     else $origin[head($path)]/f:by-path(*, tail($path))"/>
</xsl:function>

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167736

With Saxon 9.8 and XSLT 3.0 you could use a static parameter with the path expression

<xsl:param name="path" static="yes" as="xs:string" select="'/items/item[1]/item[2]'"/>

and where you want to use that path you would not use a normal select attribute but the corresponding shadow attribute _select="{$path}" instead e.g.

<xsl:template match="/">
  <xsl:copy-of _select="{$path}"/>
</xsl:template>

You can then set that parameter when you run the stylesheet like any other parameters.

Upvotes: 0

Related Questions