嗨,我已经执行了一个转换,如果它是null,则删除一个标记 .
我想检查我的转换是否正常工作,所以不是手动检查,而是编写了一个XSLT代码,只检查OUTPUT XML中是否存在该特定标记,如果它为null,则第二个XSLT应该输出一个文字“发现” . (我实际上并不需要一些XML类型的输出,但我只是使用XSLT进行搜索 . )
当我尝试使用这个XSL代码::
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/SiebelMessage//SuppressCalendar[.!='']">
FOUND
</xsl:template>
</xsl:stylesheet>
它输出XML文件中存在的所有TEXT DATA,
为了避免这种情况,我不得不写下这段代码::
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/SiebelMessage//SuppressCalendar[.!='']">
FOUND
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
为什么以前的代码输出TEXT,为什么我要坚持XSL忽略所有其他文本?是所有XML解析器的行为或仅我自己的行为(我正在使用msxml解析器) .
2 回答
You are discovering one of the most fundamental XSLT features as specified in the Specification: the built-in templates of XSLT .
From the Spec :
因此,报告的行为是应用内置模板的结果 - 这三个模板中的第一个和第二个 .
It is a good XSLT design pattern to override the built-in templates 与您自己一起发出错误消息,以便程序员立即知道他的转换是"leaking":
For example ,如果有这个XML文档:
and it is processed with this transformation :
the result is :
并且程序员将非常混淆不需要的文本是如何出现的 .
However, just adding this catch-all template helps avoid any such confusion and catch errors immediately :
Now, besides the confusing output the programmer gets a warning that explains the problem immediately :
Later Addition by Michael Kay for XSLT 3.0
在XSLT 3.0中,您可以在
xsl:mode
声明上指定回退行为,而不是添加catch-all模板规则 . 例如,<xsl:mode on-no-match="shallow-skip"/>
导致跳过所有不匹配的节点(包括文本节点),而<xsl:mode on-no-match="fail"/>
将不匹配视为错误,<xsl:mode warning-on-no-match="true"/>
导致警告 .在XSL中有几个built in template rules,其中一个是这样的:
它输出文字 .