XSLT如何根据条件选择返回空报文或执行对应转换操作
XSLT条件命中时输出空报文的解决方法
问题原因
你当前的代码逻辑本身没有语法错误,之所以会触发原报文输出,是因为部分XSLT处理器存在内置默认规则:当根节点模板没有输出任何内容时,会自动调用递归复制逻辑处理所有节点,最终输出未经转换的原始报文。
解决方法
只需要在条件命中的<xsl:when>块中明确输出空内容,即可阻止默认规则触发,完全符合你需要的输出效果,修改后的完整XSLT代码如下:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" encoding="UTF-8"/> <xsl:template match="/"> <xsl:choose> <xsl:when test="A1/B1/C1[text() = 'SI']"> <!-- 明确输出空内容,阻止默认复制规则触发 --> <xsl:value-of select="''"/> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="@*|node()"/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="A1"> <A1 Orig="22"> <xsl:apply-templates select="node()|@*"/> </A1> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
额外说明
- 如果你需要完全空的输出(连XML声明都不需要),可以在
<xsl:output>标签中添加omit-xml-declaration="yes"属性即可。 - 测试时如果发现条件没有命中,可以先在
<xsl:when>块中输出临时测试节点,验证判断条件的路径是否正确。
内容的提问来源于stack exchange,提问作者agm
相关产品推荐
相关产品推荐

