XSLT如何删除Data下值非S01/S03的Status标签 | 匹配运算符问题
问题原因
你的代码存在两处核心错误:
- 空模板匹配对象错误:你写的空模板匹配的是整个
Data节点,触发后会直接删除整段Data内容,和你仅要移除不符合条件的Status节点的需求不符。 - 判断逻辑错误:你用节点匹配并集运算符
|搭配不等于判断的写法,实际生效的逻辑是「Status取值不是S01 或 不是S03」,该条件会覆盖所有取值场景:取值为S01时满足「不是S03」,取值为S03时满足「不是S01」,取值为S02时两者都满足,最终会导致所有Data节点都被删除。
修改方案
- 删掉原有错误的匹配
Data节点的空模板 - 新增专门匹配不符合要求的
Status节点的空模板,判断逻辑改为「取值不等于S01 且 不等于S03」,匹配到对应节点后直接不输出即可。
修改后的完整XSLT代码如下:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" xmlns:ns0="http://localhost" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="ns0:root"> <xsl:variable name="condition" select="ns0:Student[ns0:BirthPlace/ns0:Zone='PNH']" /> <xsl:if test="$condition"> <xsl:copy> <xsl:copy-of select="@* | ns0:Class "/> <xsl:apply-templates select="$condition"/> </xsl:copy> </xsl:if> </xsl:template> <xsl:template match="ns0:Student"> <xsl:copy> <xsl:apply-templates select="ns0:BirthPlace|ns0:Data"/> </xsl:copy> </xsl:template> <xsl:template match="ns0:BirthPlace"> <xsl:copy> <xsl:copy-of select="ns0:Province|ns0:Distance"/> </xsl:copy> </xsl:template> <xsl:template match="ns0:Data"> <xsl:copy> <xsl:apply-templates select="ns0:Time|ns0:Status"/> </xsl:copy> </xsl:template> <xsl:template match="ns0:Time"> <xsl:copy> <xsl:copy-of select="@* | node()"/> </xsl:copy> </xsl:template> <xsl:template match="ns0:Status"> <xsl:copy> <xsl:copy-of select="@* | node()"/> </xsl:copy> </xsl:template> <!-- 匹配取值不是S01也不是S03的Status节点,直接不输出 --> <xsl:template match="ns0:Status[. != 'S01' and . != 'S03']"/> </xsl:stylesheet>
修改后仅会自动过滤取值为S02的Status节点,其余内容保留,和你预期输出完全一致。
内容的提问来源于stack exchange,提问作者Veasna
相关产品推荐
相关产品推荐

