Storing Nodes in XSL Variables
Posted: March 8th, 2024, 5:12 pm
When using XPaths, the result of an XPath can be stored in a variable using the "select" attribute:
This only works with the "select" attribute, and will NOT work with content inside of a variable node:
This can help in situations where, for example, multiple values are needed from a node with a complicated XPath:
It also allows easier access to a node or list of nodes within a for-each:
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>