【发布时间】:2009-05-22 22:27:08
【问题描述】:
我的要求是 - 使用 XSLT- 显示一个包含美国各州的下拉列表,并且 打印 在将使用我的样式表的 XML 中声明的特定对象上“选择”。
我正在考虑声明一个包含状态的数组并对其进行迭代,但我不知道该怎么做。
注意:欢迎提供更多想法;)
【问题讨论】:
标签: arrays xslt drop-down-menu iteration
我的要求是 - 使用 XSLT- 显示一个包含美国各州的下拉列表,并且 打印 在将使用我的样式表的 XML 中声明的特定对象上“选择”。
我正在考虑声明一个包含状态的数组并对其进行迭代,但我不知道该怎么做。
注意:欢迎提供更多想法;)
【问题讨论】:
标签: arrays xslt drop-down-menu iteration
一种方法是将状态数据嵌入样式表本身,并使用document('') 访问样式表文档,如下所示:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="whatever"
exclude-result-prefixes="my">
<xsl:output indent="yes"/>
<!-- The value of the state you want to select, supplied in the input XML -->
<xsl:variable name="selected-state" select="/xpath/to/state/value"/>
<!-- You have to use a namespace, or the XSLT processor will complain -->
<my:states>
<option>Alabama</option>
<option>Alaska</option>
<!-- ... -->
<option>Wisconsin</option>
<option>Wyoming</option>
</my:states>
<xsl:template match="/">
<!-- rest of HTML -->
<select name="state">
<!-- Access the embedded document as an internal "config" file -->
<xsl:apply-templates select="document('')/*/my:states/option"/>
</select>
<!-- rest of HTML -->
</xsl:template>
<!-- Copy each option -->
<xsl:template match="option">
<xsl:copy>
<!-- Add selected="selected" if this is the one -->
<xsl:if test=". = $selected-state">
<xsl:attribute name="selected">selected</xsl:attribute>
</xsl:if>
<xsl:value-of select="."/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
如果您有任何问题,请告诉我。
【讨论】:
理想情况下,您应该将状态列表存储在 XML 文件中,然后使用 XSLT 对其进行迭代。
更新: 如果您无法编辑 XML,您可以考虑使用 document function 从第二个数据文件加载数据:
【讨论】: