XSL 应用模板优先级

dge*_*e03 1 xml xslt

我有问题,我需要你。

我有一个想法用以下代码来解决它:

<xsl:template match="root">
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="*[@foo]" priority="3">
    <p>This text must be systematically added for any rendered element having a foo attribute</p>
    <xsl:apply-templates select="."/>
</xsl:template>

<xsl:template match="bar1">
    <p>This is the normal rendering for the bar1 element</p>
</xsl:template>
<xsl:template match="bar1[@class='1']">
    <p>This is the normal rendering for the bar1 element with class 1</p>
</xsl:template>
<xsl:template match="bar1[@class='2']">
    <p>This is the normal rendering for the bar1 element with class 2</p>
</xsl:template>
...
<xsl:template match="barN">
    <p>This is the normal rendering for the barN element</p>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

当我尝试将此 xsl 应用于以下 xml 时:

<root>
    <bar1 foo="1"></bar1>
    <bar1 foo="1" class="1"></bar1>
    <bar1 class="2"></bar1>
    <bar1></bar1>
    ...
    <barN foo="n"></barN>
    <barN></barN>
</root>
Run Code Online (Sandbox Code Playgroud)

XSLT 引擎在priority="3" 模板上无限循环,而不是(根据我的需要)首先应用priority="3" 模板一次,然后应用bar1 .. barN 模板。

如何在不修改每个 bar1 .. barN 模板 (N~=150) 的情况下执行此操作以在具有 foo 属性的每个元素上添加系统文本?

Ian*_*rts 5

<xsl:apply-templates select="."/>总是会选择最具体的模板,这确实可能导致无限递归。如果您使用的是 XSLT 2.0 那么您可以使用

<xsl:next-match/>
Run Code Online (Sandbox Code Playgroud)

相反,它会选择当前正在执行的模板之后的下一个最高优先级模板。在 XSLT 1.0 中,唯一的选择是将通用模板移动到另一个.xsl文件中,让您的主模板导入该文件,然后使用“较低导入优先级”应用模板(即仅考虑导入文件中的模板,而不考虑<xsl:apply-imports/>导入文件中的模板)。导入)。

类.xsl

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:template match="bar1">
        <p>This is the normal rendering for the bar1 element</p>
    </xsl:template>
    <xsl:template match="bar1[@class='1']">
        <p>This is the normal rendering for the bar1 element with class 1</p>
    </xsl:template>
    <xsl:template match="bar1[@class='2']">
        <p>This is the normal rendering for the bar1 element with class 2</p>
    </xsl:template>
    ...
    <xsl:template match="barN">
        <p>This is the normal rendering for the barN element</p>
    </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

主文件.xsl

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:import href="classes.xsl" />

    <xsl:template match="*[@foo]" priority="3">
        <p>This text must be systematically added for any rendered element having a foo attribute</p>
        <xsl:apply-imports/>
    </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)