Using the xsl: variable in an xsl: foreach select expression

I am trying to iterate through an XML document using xsl: foreach, but I need select = "" to be dynamic, so I use the variable as the source. Here is what I 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">

...

An error was specified in foreach: "XslTransformException. To use a fragment of the resulting tree in a path expression, first convert it to node-set using the msxsl: node -set () function.

When I use the msxsl: node -set () function, my results are empty.

I know that I am setting $ DataPath to a string, but should the node -set () function not create a node from it? Am I missing something? When I do not use a variable:

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

I get the right results.

Here is the XML data file I am 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>

, foreach ?

+3
3

:

   <xsl:for-each select="/Rating[Type='1']/Path1/*
                         |
                          /Rating[Type='2']/Path2/*">
+3

XSLT 1.0 xpaths. , , , node, :

<xsl:variable name="Type" select="/Rating/Type"/>
<xsl:choose>
    <xsl:when test="$Type='1'">
        <xsl:call-template name="DoStuff">
            <xsl:with-param name="Input" select="/Rating/Path1/*"/>
        </xsl:call-template>
    </xsl:when>
    <xsl:when test="$Type='2'">
        <xsl:call-template name="DoStuff">
            <xsl:with-param name="Input" select="/Rating/Path2/*"/>
        </xsl:call-template>
    </xsl:when>
</xsl:choose>

...

<xsl:template name="DoStuff">
    <xsl:param name="Input"/>
    <xsl:for-each select="$Input">
        <!-- Do stuff with input -->
    </xsl:for-each>
</xsl:template>
+3

node-set(), , node -sets, . : XSLT .

SetDataPath , $DataPath. <xsl:for-each select="$DataPath">, XSLT- , DataPath node -set, .

, , / XPath. , .

Show your XML input and specify the transformation you want to do, and I will try to show you a way to do this.

0
source

Source: https://habr.com/ru/post/1737028/


All Articles