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

XSLT 1.0转换XML时跳过指定元素、提取内容并格式化输出的实现方法

修改后的完整XSLT 1.0代码

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/products">
    <xsl:copy>
        <xsl:apply-templates select="group/product"/>
    </xsl:copy>
</xsl:template> 

<xsl:template match="product">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <!-- 替换原来的copy-of为apply-templates,触发子节点自定义处理逻辑 -->
        <xsl:apply-templates select="*"/>
    </xsl:copy>
</xsl:template>   

<xsl:template match="@*">
    <xsl:element name="{name()}">
        <xsl:value-of select="."/>
    </xsl:element>
</xsl:template>  

<xsl:template match="@symbol">
    <symbol>
        <xsl:text>CPF-</xsl:text>
        <xsl:value-of select="."/>
    </symbol>
</xsl:template>  

<!-- 新增:处理category节点,仅保留name的文本内容 -->
<xsl:template match="category">
    <category>
        <xsl:value-of select="name"/>
    </category>
</xsl:template>

<!-- 新增:处理images节点,不输出外层标签,直接处理内部gfx -->
<xsl:template match="images">
    <xsl:apply-templates select="gfx"/>
</xsl:template>

<!-- 新增:处理gfx节点,按顺序加序号后缀 -->
<xsl:template match="gfx">
    <xsl:element name="gfx{position()}">
        <xsl:value-of select="."/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

核心改动说明

  • 将product模板中原有的xsl:copy-of select="*"替换为xsl:apply-templates select="*",支持子节点的自定义转换逻辑
  • 新增category节点匹配规则:直接输出category标签,内容提取自其子节点name的文本,自动丢弃id标签
  • 新增images节点匹配规则:不输出外层images标签,直接遍历内部的gfx节点
  • 新增gfx节点匹配规则:用position()函数获取节点的出现顺序,动态生成带序号的标签名(gfx1/gfx2...)

用上述代码转换对应输入XML,得到的输出完全符合需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 06:36:03