我的要求是 - 使用 XSLT - 显示美国各州的下拉列表,并在将使用我的样式表的 XML 中声明的特定对象上打印“已选择”。
我正在考虑用状态声明一个数组并对其进行迭代,但我不知道该怎么做。
注意:欢迎更多想法;)
我的要求是 - 使用 XSLT - 显示美国各州的下拉列表,并在将使用我的样式表的 XML 中声明的特定对象上打印“已选择”。
我正在考虑用状态声明一个数组并对其进行迭代,但我不知道该怎么做。
注意:欢迎更多想法;)
一种方法是将状态数据嵌入样式表本身,并使用 访问样式表文档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,您可以查看使用文档功能从第二个数据文件加载数据: