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

如何在XSLT中创建类字典变量或索引,用于后续匹配键处理XML?

解决方案:XSLT实现带星号标记的页码转换

没问题!我帮你搞定这个需求,核心思路是先给每个引用建立一个“位置索引”,然后遍历<p>里的内容,把每个<page>节点替换成对应星号数量的标记。

实现步骤说明

  1. 建立引用索引:用xsl:key把每个<reference>的文本和它在列表中的位置绑定起来,这样能快速通过引用文本找到它的位置——位置数就是星号的数量,比如第1个引用对应1个星,第2个对应2个星。
  2. 递归处理内容:遍历<p>的子节点,文本直接输出;遇到<page>节点时,根据referenceAttribute找到对应的引用位置,生成对应数量的星号,再和页码拼接成要求的格式。

完整XSLT代码

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- 定义key:通过引用文本快速查找对应的reference节点 -->
    <xsl:key name="ref-by-text" match="reference" use="text()"/>

    <!-- 匹配根节点,启动处理流程 -->
    <xsl:template match="/">
        <xsl:apply-templates select="a/c/d/p"/>
    </xsl:template>

    <!-- 处理p元素,递归处理所有子节点 -->
    <xsl:template match="p">
        <xsl:apply-templates/>
    </xsl:template>

    <!-- 处理文本节点,直接输出内容(自动去除多余空格) -->
    <xsl:template match="text()">
        <xsl:value-of select="normalize-space(.)"/>
    </xsl:template>

    <!-- 处理page节点,生成带星号的页码标记 -->
    <xsl:template match="page">
        <!-- 获取当前引用在列表中的位置(从1开始计数) -->
        <xsl:variable name="ref-position" select="count(key('ref-by-text', @referenceAttribute)/preceding-sibling::reference) + 1"/>
        <!-- 生成对应数量的星号 -->
        <xsl:variable name="stars">
            <xsl:call-template name="generate-stars">
                <xsl:with-param name="count" select="$ref-position"/>
            </xsl:call-template>
        </xsl:variable>
        <!-- 拼接成最终格式:[**页码] -->
        <xsl:text> [</xsl:text>
        <xsl:value-of select="$stars"/>
        <xsl:value-of select="@number"/>
        <xsl:text>] </xsl:text>
    </xsl:template>

    <!-- 辅助模板:生成指定数量的星号 -->
    <xsl:template name="generate-stars">
        <xsl:param name="count"/>
        <xsl:if test="$count > 0">
            <xsl:text>*</xsl:text>
            <xsl:call-template name="generate-stars">
                <xsl:with-param name="count" select="$count - 1"/>
            </xsl:call-template>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

效果验证

把你提供的XML输入这个XSLT后,输出结果正好是:

Sample text [**199] Sample text 1 [*17] Sample text 2 [**200] Sample text 3

完全匹配你要的格式,星号数量严格对应引用在<references>列表中的位置~

内容的提问来源于stack exchange,提问作者VladS123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:16:51