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

如何在XSLT 1.0中将XML片段存入变量并在<apply-templates>中使用?

XSLT 1.0 节点集处理与模板匹配问题

原始XML

<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
</catalog>

当前XSLT 1.0代码

<xsl:template match="catalog">
  <xsl:variable name="var">
    <content>
      <xsl:copy-of select="cd"/>
    </content>
  </xsl:variable>
<xsl:apply-templates select="$var"/>
</xsl:template>

需求说明

  1. 期望变量$var生成如下XML结构:
<content>
  <title>Empire Burlesque</title>
  <artist>Bob Dylan</artist>
  <country>USA</country>
  <company>Columbia</company>
  <price>10.90</price>
  <year>1985</year>
</content>
  1. 需要触发匹配<content>节点的模板<xsl:template match="content">

解决方案

XSLT 1.0中,用<xsl:variable>生成的内容默认是结果树片段,无法直接通过<xsl:apply-templates>处理节点。必须先通过扩展函数node-set()将其转换为可遍历的节点集。

修改后的完整XSLT代码

<xsl:stylesheet version="1.0" 
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:exsl="http://exslt.org/common"
                extension-element-prefixes="exsl">

  <xsl:template match="catalog">
    <xsl:variable name="var">
      <content>
        <!-- 直接复制cd的子节点而非整个cd元素,满足期望结构 -->
        <xsl:copy-of select="cd/*"/>
      </content>
    </xsl:variable>
    <!-- 将结果树片段转为节点集后应用模板 -->
    <xsl:apply-templates select="exsl:node-set($var)/content"/>
  </xsl:template>

  <!-- 匹配content节点的模板 -->
  <xsl:template match="content">
    <!-- 这里写你需要的处理逻辑,比如输出或进一步处理子节点 -->
    <div class="cd-content">
      <xsl:apply-templates/>
    </div>
  </xsl:template>

  <!-- 可选:匹配cd子节点的模板,自定义输出 -->
  <xsl:template match="title">
    <h3><xsl:value-of select="."/></h3>
  </xsl:template>

  <xsl:template match="artist|country|company|price|year">
    <p><strong><xsl:value-of select="local-name()"/></strong>: <xsl:value-of select="."/></p>
  </xsl:template>

</xsl:stylesheet>

关键说明

  • 命名空间引入:添加exsl命名空间并声明扩展前缀,确保node-set()函数可用(多数主流XSLT处理器如Saxon、Xalan都支持EXSLT扩展)。
  • 节点集转换:通过exsl:node-set($var)将结果树片段转为节点集,之后即可通过路径选择<content>节点并应用模板。
  • 结构修正:原代码中<xsl:copy-of select="cd"/>会复制整个<cd>元素,改为<xsl:copy-of select="cd/*"/>直接复制其子节点,符合期望的<content>内部结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:10:46