2

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?

  • Why don't you simply convert the $result variable to a node-set, using the node-set() function - just like your error message suggests? – michael.hor257k Jul 15 '15 at 11:02
  • I know that is the solution for removing the exception. However, when I want to call this template from many different templates I would have to add the `node-set()` function with each call. Besides, if no 'special' calls would be nescesary for a template, it would increase maintainability. – Jasper Saaltink Jul 15 '15 at 11:30
  • 1
    "*I would have to add the node-set() function with each call.*" Not if you define another variable as ``. I do that routinely - that's just how XSLT 1.0 works. – michael.hor257k Jul 15 '15 at 11:38

1 Answers1

3

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.

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110