【问题标题】:How to declare and iterate an array in XSLT?如何在 XSLT 中声明和迭代数组?
【发布时间】:2009-05-22 22:27:08
【问题描述】:

我的要求是 - 使用 XSLT- 显示一个包含美国各州的下拉列表,并且 打印 在将使用我的样式表的 XML 中声明的特定对象上“选择”。

我正在考虑声明一个包含状态的数组并对其进行迭代,但我不知道该怎么做。

注意:欢迎提供更多想法;)

【问题讨论】:

    标签: arrays xslt drop-down-menu iteration


    【解决方案1】:

    一种方法是将状态数据嵌入样式表本身,并使用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>
    

    如果您有任何问题,请告诉我。

    【讨论】:

    • 难道也可以将 my:states 节点放在变量声明中并在 select 表达式中使用此变量吗?
    • 在 XSLT 2.0 中,是的。在 XSLT 1.0 中,您需要使用扩展函数,例如 exsl:node-set() 或 msxsl:node-set()。 document('') 解决方案都不需要。
    【解决方案2】:

    理想情况下,您应该将状态列表存储在 XML 文件中,然后使用 XSLT 对其进行迭代。

    更新: 如果您无法编辑 XML,您可以考虑使用 document function 从第二个数据文件加载数据:

    【讨论】:

    • 我无法更改 XML,它是由另一个系统提供的
    • 您仍然可以使用 document 函数访问另一个包含状态列表的静态 XML 文档,对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 2012-12-05
    • 2014-01-22
    • 2017-05-10
    相关资源
    最近更新 更多