【问题标题】:XSLT1.0 Looping over self-referenced dataXSLT1.0 循环自引用数据
【发布时间】:2026-01-30 23:00:01
【问题描述】:

我有一个静态的 xsl 国家/地区列表,我希望能够使用预选值调用这些国家/地区。为此,需要遍历每个节点并进行简单检查(最好同时将国家/地区自包含在同一文件中)。但是,执行 有效,但在同一表达式上执行 却不行——这是怎么回事?这可能吗?

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:isoCountry="isoCountry:country">
  <isoCountry:country>
      <option value=""></option>
      <option value="AU">Australia</option>
      <option value="AD">Andorra</option>
      <option value="AE">United Arab Emirates</option>
      <option value="AF">Afghanistan</option>
      <option value="AG">Antigua and Barbuda</option>
  </isoCountry:country>

  <xsl:template name="CountrySelect">
    <select>

      <option> <!-- correct number of nodes, good -->
        <xsl:value-of select="count(document('')/*/isoCountry:menu/menu/*)"/>
      </option> 

      <xsl:copy-of select="document('')/*/isoCountry:country/option"/> <!-- this works -->

      <xsl:for-each select="document('')/*/isoCountry:country/option"> <!-- this does not -->
        <option><xsl:value-of select="."/></option>
      </xsl:for-each>

    </select>
  </xsl:template>
</xsl:stylesheet>

【问题讨论】:

  • 我不确定您希望for-each 做什么。它输出包裹在option 元素中的每个country/option 的文本值。如果您想要option 的副本,请使用&lt;xsl:copy-of select="."/&gt;
  • 嘿,谢谢你的回复,目的是做类似

标签: xml xslt


【解决方案1】:

下面是一个使用param 调用CountrySelect 模板的示例,以在value 属性匹配时生成selected 属性。

<xsl:stylesheet
        version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:isoCountry="isoCountry:country"
        exclude-result-prefixes="isoCountry">

    <xsl:output method="html"/>

    <isoCountry:country>
        <option value=""/>
        <option value="AU">Australia</option>
        <option value="AD">Andorra</option>
        <option value="AE">United Arab Emirates</option>
        <option value="AF">Afghanistan</option>
        <option value="AG">Antigua and Barbuda</option>
    </isoCountry:country>

    <xsl:template match="/">
        <form>
            <xsl:call-template name="CountrySelect">
                <xsl:with-param name="selected">AU</xsl:with-param>
            </xsl:call-template>
        </form>
    </xsl:template>

    <xsl:template name="CountrySelect">
        <xsl:param name="selected"/>
        <select>
            <xsl:for-each select="document('')/*/isoCountry:country/option">
                <xsl:element name="{name()}"> <!-- could just be name="option" -->
                    <xsl:if test="$selected=@value">
                        <xsl:attribute name="selected">true</xsl:attribute>
                    </xsl:if>
                    <xsl:copy-of select="@*"/>
                    <xsl:copy-of select="text()"/>
                </xsl:element>
            </xsl:for-each>
        </select>
    </xsl:template>
</xsl:stylesheet>

【讨论】: