Search code examples
templatesxslttransformxslt-1.0node-set

How to return a node-set with a template


I'm trying to convert a datetime string to a node based datetime in XSLT 1.0. basically I want to go from

31-12-2014

to:

<Date>
    <Day>31</Day
    <Month>12</Month>
    <Year>2014</Year>
</Date>

To achieve this I created this template:

<xsl:template name="ToDTNodes">
  <xsl:param name="dateTimeString"/>

  <xsl:variable name="date" select="substring($dateTimeString,1,10)"/>
  <xsl:variable name="result">
    <DtNode>
      <Year>
        <xsl:value-of select="substring($date,7,4)"/>
      </Year>
      <Month>
        <xsl:value-of select="substring($date,4,2)"/>
      </Month>
      <Day>
        <xsl:value-of select="substring($date,1,2)"/>
      </Day>
    </DtNode>
  </xsl:variable>

  <xsl:copy-of select="msxsl:node-set($result)/DtNode"/>
</xsl:template>

I try to make the template return a node/set instead of a fragment. Note that I also tried this without the /DtNode on the end. That would enable me to call this template without using the node-set function with eacht call.

Sadly I get an exception when trying to access a child:

XslTransformException: To use a result tree fragment in a path expression, first convert it to a node-set using the msxsl:node-set() function

when I try to do this:

<xsl:variable name="result">
  <xsl:call-template  name="ToDTNodes">
    <xsl:with-param name="dateTimeString" select="$SomeNode/BeginDate" />
  </xsl:call-template>
</xsl:variable>

<Value>
  <xsl:value-of select="$result/Year"/>
</Value>

Is there any way to get a template to return a node-set instead of a string or result tree fragement?


Solution

  • No, with XSLT 1.0 you would need to use an extension element like http://exslt.org/func/elements/result/index.html within an http://exslt.org/func/elements/function/index.html to be able to return a node set and not a result tree fragment. A template will always return a result tree fragment.