You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为XSL生成的表格行正确设置带前缀的递增ID?

解决XSLT中动态设置元素ID的问题

你当前的写法错误在于直接在HTML属性中嵌套<xsl:value-of>,这不符合XSLT的语法规范,Firefox提示格式不正确正是因为这个原因。下面提供两种正确的实现方式:

方法1:使用属性值模板(推荐)

属性值模板是XSLT中简化动态属性生成的语法,用大括号{}包裹XPath表达式即可:

<xsl:template match="item">
  <xsl:variable name="item.count" select="count(preceding::item)" />
  <tr id="item-{$item.count}">
    <xsl:comment><xsl:value-of select="$item.count" />: <xsl:value-of select="." /></xsl:comment>
    <xsl:apply-templates select="./*"/>
    <!-- ... -->
    <td>(output)</td>
  </tr>
</xsl:template>

方法2:使用<xsl:attribute>元素

如果需要更复杂的属性生成逻辑,可以显式使用<xsl:attribute>来创建ID属性:

<xsl:template match="item">
  <xsl:variable name="item.count" select="count(preceding::item)" />
  <tr>
    <xsl:attribute name="id">item-<xsl:value-of select="$item.count" /></xsl:attribute>
    <xsl:comment><xsl:value-of select="$item.count" />: <xsl:value-of select="." /></xsl:comment>
    <xsl:apply-templates select="./*"/>
    <!-- ... -->
    <td>(output)</td>
  </tr>
</xsl:template>

额外补充:count(preceding::item)会统计当前节点之前所有的item节点,计数从0开始。如果需要从1开始递增,可以改成count(preceding::item) + 1。

内容的提问来源于stack exchange,提问作者U. Windl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:54:58