我有问题,我需要你。
我有一个想法,用以下代码解决它:
<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>
当我尝试在以下xml上应用此xsl时:
<root>
<bar1 foo="1"></bar1>
<bar1 foo="1" class="1"></bar1>
<bar1 class="2"></bar1>
<bar1></bar1>
...
<barN foo="n"></barN>
<barN></barN>
</root>
XSLT引擎在priority =“3”模板上无休止地循环,而不是(根据我的需要)首先应用priority =“3”模板,然后应用bar1 .. barN模板。
如何在不修改每个bar1 .. barN模板(N~ = 150)的情况下执行此操作,以在每个具有foo属性的元素上添加系统文本?
答案 0 :(得分:4)
<xsl:apply-templates select="."/>
将始终选择最具体的模板,这可能确实会导致无限递归。如果您使用的是XSLT 2.0,则可以使用
<xsl:next-match/>
相反,它在当前正在执行的模板之后选择次高优先级模板。在XSLT 1.0中,唯一的选择是将通用模板移动到不同的.xsl
文件中,让主要模板导入,然后使用<xsl:apply-imports/>
应用具有“较低导入优先级”的模板(即仅考虑导入 ed 文件中的模板,而不是导入 ing 文件。
<强> classes.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>
<强> main.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>
答案 1 :(得分:0)
您可以使用模板模式。
<xsl:template match="*[@foo]">
<p>This text must be systematically added for any rendered element having a foo attribute</p>
<xsl:apply-templates select="." mode="normal" />
</xsl:template>
<xsl:template match="bar1" mode="normal">
<p>This is the normal rendering for the bar1 element</p>
</xsl:template>
<!-- ... -->
<xsl:template match="barN" mode="normal">
<p>This is the normal rendering for the barN element</p>
</xsl:template>
关键是,当<xsl:template match="*[@foo]">
匹配某些内容而你在其中调用一个简单的<xsl:apply-templates select="." />
时,相同的模板当然会再次匹配。