如何简化将choice结构转换为app结构的XSLT代码?
优化后的XSLT转换方案
你的代码逻辑本身是正确的,确实可以优化得更简洁紧凑。以下是几种更优雅的实现方式:
1. XSLT 1.0/2.0 兼容的精简版本
这个版本保留了原代码的清晰结构,通过合并冗余换行让代码更紧凑:
<xsl:template match="choice"> <app><xsl:apply-templates/></app> </xsl:template> <xsl:template match="sic"> <lem><xsl:apply-templates/></lem> </xsl:template> <xsl:template match="corr[@type='erratum']"> <rdg wit="{@type}"><xsl:apply-templates/></rdg> </xsl:template>
- 核心转换逻辑和你的原代码完全一致,只是减少了视觉上的冗余感。
- 属性值模板
{@type}的用法已经高效简洁,无需修改。
2. XSLT 3.0 更简洁版本(推荐,若环境支持)
如果你的XSLT处理器支持3.0版本,可以利用<xsl:mode>特性自动处理无需转换的元素,省去手动编写身份模板的步骤:
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:mode on-no-match="shallow-copy"/> <xsl:template match="choice"> <app><xsl:apply-templates/></app> </xsl:template> <xsl:template match="sic"> <lem><xsl:apply-templates/></lem> </xsl:template> <xsl:template match="corr[@type='erratum']"> <rdg wit="{@type}"><xsl:apply-templates/></rdg> </xsl:template> </xsl:stylesheet>
<xsl:mode on-no-match="shallow-copy"/>会自动复制所有未匹配的元素、属性和文本,无需额外编写模板。- 代码仅聚焦于需要转换的节点,逻辑更清晰。
补充说明
你的原代码其实已经很规范,之所以觉得冗长可能是模板拆分带来的视觉效果。上述优化方案在不改变转换逻辑的前提下,通过紧凑写法或新版本特性,让代码更简洁优雅,同时保持可读性。
内容的提问来源于stack exchange,提问作者piah
相关产品推荐
相关产品推荐

