Using xsl:variable in a xsl:foreach select statment

Posted by Nefariousity on Stack Overflow See other posts from Stack Overflow or by Nefariousity
Published on 2010-03-15T17:12:26Z Indexed on 2010/03/15 18:49 UTC
Read the original article Hit count: 1434

Filed under:
|
|
|

I'm trying to iterate through an xml document using xsl:foreach but I need the select=" " to be dynamic so I'm using a variable as the source. Here's what I've tried:

...

<xsl:template name="SetDataPath">
  <xsl:param name="Type" />

  <xsl:variable name="Path_1">/Rating/Path1/*</xsl:variable>
  <xsl:variable name="Path_2">/Rating/Path2/*</xsl:variable>

  <xsl:if test="$Type='1'">
    <xsl:value-of select="$Path_1"/>
  </xsl:if>

  <xsl:if test="$Type='2'">
    <xsl:value-of select="$Path_2"/>
  </xsl:if>
<xsl:template>

...

    <!-- Set Data Path according to Type -->
  <xsl:variable name="DataPath">
    <xsl:call-template name="SetDataPath">
      <xsl:with-param name="Type" select="/Rating/Type" />
    </xsl:call-template> 
  </xsl:variable>

...

<xsl:for-each select="$DataPath">

...

The foreach threw an error stating: "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 use the msxsl:node-set() function though, my results are blank.

I'm aware that I'm setting $DataPath to a string, but shouldn't the node-set() function be creating a node set from it? Am I missing something? When I don't use a variable:

<xsl:for-each select="/Rating/Path1/*">

I get the proper results.

Here's the XML data file I'm using:

<Rating>
    <Type>1</Type>
    <Path1>
       <sarah>
          <dob>1-3-86</dob>
          <user>Sarah</user>
       </sarah>
       <joe>
          <dob>11-12-85</dob>
          <user>Joe</user>
       </joe>
    </Path1>
    <Path2>
       <jeff>
          <dob>11-3-84</dob>
          <user>Jeff</user>
       </jeff>
       <shawn>
          <dob>3-5-81</dob>
          <user>Shawn</user>
       </shawn>
    </Path2>
</Rating>

My question is simple, how do you run a foreach on 2 different paths?

© Stack Overflow or respective owner

Related posts about xslt

Related posts about xsl