XSL模板优先级

时间:2011-04-18 22:20:42

标签: xslt operator-precedence

我有2个模板

<template match="vehicle_details[preceding-sibling::vehicle_type = '4x4']/*">
    ...
</xsl:template>
<xsl:template match="vehicle_details[descendant::color = 'red']/*" >
    ...
</xsl:template>

我的问题是:哪个模板优先于转换。有人可以给我一个关于XSL模板优先级的概述/资源吗?

提前致谢!

1 个答案:

答案 0 :(得分:43)

section 5.5 of the XSLT spec中描述了完整的解决方案流程。

一般而言,以下规则按顺序适用(例如,由于导入优先级较低而被排除在考虑范围之外的模板将永久消除,无论其优先级如何):

  1. 导入的模板的优先级低于主样式表中的模板
  2. priority属性值较高的模板优先级较高
  3. 没有priority属性的模板被分配了默认优先级。具有更多特定模式的模板优先。
  4. 如果前三个步骤考虑了多个模板,则会出错,但XSLT处理器可以通过默认恢复到文件中的最后一个来恢复。
  5. 在您的特定情况下,两个模板具有相同的优先级,因此适用上述#4。为了证明:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:template match=
                 "vehicle_details[preceding-sibling::vehicle_type = '4x4']/*">
            template1
        </xsl:template>
        <xsl:template match="vehicle_details[descendant::color = 'red']/*">
            template2
        </xsl:template>
    </xsl:stylesheet>
    

    应用于此输入(两个模板匹配):

    <root>
        <vehicle_type>4x4</vehicle_type>
        <vehicle_details>
            <color>red</color>
        </vehicle_details>
    </root>
    

    输出:

    template2
    

    但是如果我们交换模板的顺序:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:template match="vehicle_details[descendant::color = 'red']/*">
            template2
        </xsl:template>
        <xsl:template match=
                 "vehicle_details[preceding-sibling::vehicle_type = '4x4']/*">
            template1
        </xsl:template>
    </xsl:stylesheet>
    

    然后输出是:

    template1
    
相关问题