为何xsl:value-of行为随xsl:stylesheet版本不同而差异显著?
XSLT 1.0与2.0输出差异的原因解析
这个差异的核心是XSLT 1.0和2.0中xsl:value-of处理多节点结果的规则完全不同:
XSLT 1.0的行为逻辑
在XSLT 1.0中,xsl:value-of的select属性返回的是「节点集」。当节点集包含多个节点时,xsl:value-of只会提取节点集中第一个节点的字符串值,其余节点直接被忽略。
- 你的样式表中,
select="root/child/grandchild"会匹配到两个<grandchild>节点,但1.0仅取第一个节点的文本内容grandchild 1; - 同理,
select="root/child/yetanothergrandchild"仅取第一个对应节点的文本yetanothergrandchild 1; - 最终输出就是这两个值的拼接:
grandchild 1 yetanothergrandchild 1。
XSLT 2.0的行为逻辑
XSLT 2.0引入了「序列」的概念,替代了1.0的节点集。当xsl:value-of的select属性返回包含多个节点的序列时,它会输出序列中所有节点的字符串值,默认用空格分隔(可通过separator属性自定义分隔符)。
select="root/child/grandchild"匹配到的两个<grandchild>节点会构成一个序列,因此会依次输出两个节点的文本:grandchild 1 grandchild 2;select="root/child/yetanothergrandchild"同理输出两个节点的文本:yetanothergrandchild 1 yetanothergrandchild 2;- 两者拼接后就得到了你看到的结果:
grandchild 1 grandchild 2 yetanothergrandchild 1 yetanothergrandchild 2。
验证与兼容写法
如果需要在XSLT 2.0中模拟1.0的输出效果,只需显式指定取序列的第一个节点:
<xsl:value-of select="root/child/grandchild[1]"/> <xsl:value-of select="root/child/yetanothergrandchild[1]"/>
这样输出结果就会和XSLT 1.0完全一致。
内容的提问来源于stack exchange,提问作者Florian
相关产品推荐
相关产品推荐

