Reputation: 135
I am trying to save values from an XML doc into a variable. I am aware you can do the following:
<xsl:variable name="variableName" select="xml/node/*"/>
Below is my XML code:
<xml>
<graph2>
<averageHighTemperatures>
<January>8.3</January>
<February>8.5</February>
<March>11.1</March>
<April>13.5</April>
<May>17.1</May>
<June>20.0</June>
<July>22.6</July>
<August>22.5</August>
<September>19.3</September>
<October>15.3</October>
<November>11.2</November>
<December>9.1</December>
</averageHighTemperatures>
</graph2>
</xml>
How can I select the value of each month by specifying the node in the XML doc?
Below is my XSL:
<xsl:variable name="var" select="xml/graph2/averageHighTemperatures/*"/>
<table>
<xsl:for-each select="xml/graph2/averageHighTemperatures">
<tr>
<td><xsl:value-of select="January $var"/></td>
<td><xsl:value-of select="February $var"/></td>
</tr>
</xsl:for-each>
</table>
In the above, "January" and "February" are only being used to present the value wanted.
Upvotes: 2
Views: 1343
Reputation: 66851
Since the month names are the element names, you could select them with a predicate filter matching the local-name()
:
<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:variable name="var" select="xml/graph2/averageHighTemperatures/*"/>
<table>
<xsl:for-each select="xml/graph2/averageHighTemperatures">
<tr>
<td><xsl:value-of select="'January ', $var[local-name()='January']"/></td>
<td><xsl:value-of select="'February ', $var[local-name()='February']"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:transform>
If you are going to perform multiple lookups, then a better/faster way to select by name would be to use xsl:key
and the key()
function:
<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:key name="var" match="xml/graph2/averageHighTemperatures/*" use="local-name()"/>
<xsl:template match="/">
<table>
<xsl:for-each select="xml/graph2/averageHighTemperatures">
<tr>
<td><xsl:value-of select="'January ', key('var', 'January')"/></td>
<td><xsl:value-of select="'February ', key('var', 'February')"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:transform>
Upvotes: 1