XSL模板优先级

Mar*_*aro 23 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>
Run Code Online (Sandbox Code Playgroud)

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

提前致谢!

Way*_*ett 43

完整的分辨率过程在XSLT规范的第5.5节中描述.

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

  1. 导入的模板的优先级低于主样式表中的模板
  2. priority属性值较高的模板具有较高的优先级
  3. 没有priority属性的模板被分配了默认优先级.具有更多特定模式的模板优先.
  4. 如果前三个步骤考虑了多个模板,则会出错,但XSLT处理器可以通过默认恢复到文件中的最后一个模板来恢复.

在您的特定情况下,两个模板具有相同的优先级,因此适用上述#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>
Run Code Online (Sandbox Code Playgroud)

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

<root>
    <vehicle_type>4x4</vehicle_type>
    <vehicle_details>
        <color>red</color>
    </vehicle_details>
</root>
Run Code Online (Sandbox Code Playgroud)

输出:

template2
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

然后输出是:

template1
Run Code Online (Sandbox Code Playgroud)

  • 对于优先级值(!)很重要:最大"默认优先级"为0.5,因此您可以使用1,2等. (3认同)
  • 一个很好的解释必须清楚地表明导入优先级和"优先级"是两个不同的东西,无论导入样式表中的模板具有多高优先级,其优先级都低于导入样式表中任何模板的优先级. (2认同)
  • +1正确答案.**观察:依靠错误恢复机制是不好的做法.** (2认同)