Storing Nodes in XSL Variables

This forum allows users to post and respond to "How Do I Do ....." questions. The information contained in this forum has not been validated by K-Rise Systems and, as such, K-Rise Systems cannot guarantee the accuracy of the information.
JefferyD
Posts: 177
Joined: August 31st, 2021, 11:37 am
Contact:

Storing Nodes in XSL Variables

Unread post by JefferyD »

When using XPaths, the result of an XPath can be stored in a variable using the "select" attribute:

Code: Select all

<xsl:variable name="firstTable" select="WorkData/DataSchema/Output/Result/Table[1]"/>

This only works with the "select" attribute, and will NOT work with content inside of a variable node:

Code: Select all

<xsl:variable name="firstTable">
  <xsl:copy-of select="WorkData/DataSchema/Output/Result/Table[1]"/>
</xsl:variable>

This can help in situations where, for example, multiple values are needed from a node with a complicated XPath:

Code: Select all

<Table>
  <Name><xsl:value-of select="WorkData/DataSchema/Output/Result/Table[1]/Name"/></Name>
  <Columns>
    <xsl:for-each select="WorkData/DataSchema/Output/Result/Table[1]/Column">
      <Column><xsl:value-of select="Name"/></Column>
    </xsl:for-each>
  </Columns>
</Table>

<!-- Both of these would produce the same XML result -->

<xsl:variable name="firstTable" select="WorkData/DataSchema/Output/Result/Table[1]"/>

<Table>
  <Name><xsl:value-of select="$firstTable/Name"/></Name>
  <Columns>
    <xsl:for-each select="$firstTable/Column">
      <Column><xsl:value-of select="Name"/></Column>
    </xsl:for-each>
  </Columns>
</Table>

It also allows easier access to a node or list of nodes within a for-each:

Code: Select all

<!-- Store list of columns to display in a variable -->
<xsl:variable name="columnList" select="WorkData/DataSchema/Output/Result/Table[1]/Column[Visible='True']"/>

<Records>
  <!-- Loop on query records -->
  <xsl:for-each select="WorkData/DBRecords/Output/Result">
  
    <!-- Store node of current record in a variable -->
    <xsl:variable name="currentRecord" select="."/>
    <Record>
    
      <!-- Loop on columns to display using variable -->
      <xsl:for-each select="$columnList">
        <xsl:element name="{Name}">
        
          <!-- Get child node value of the current record where the child node name matches the name of the current column -->
          <xsl:value-of select="$currentRecord/*[name()=current()/Name]"/>
        </xsl:element>
      </xsl:for-each>
    </Record>
  </xsl:for-each>
</Records>
word count: 300

Tags:
Post Reply