我正在尝试将XML文档中的值保存到变量中。我知道您可以执行以下操作:
<xsl:variable name="variableName" select="xml/node/*"/>
下面是我的XML代码:
<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>
如何通过在XML文档中指定节点来选择每月的值?
下面是我的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>
在上面,“一月”和“二月”仅用于表示所需的值。
答案 0 :(得分:1)
由于月份名称是元素名称,因此可以使用与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>
如果要执行多个查找,则按名称选择的更好/更快的方法是使用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>