假设我有以下XML:
<root>
<a>1</a>
<b>2</b>
<a>3</a>
<c>4</c>
<a>5</a>
<a>6</a>
<b>7</b>
<a>8</a>
<c>9</c>
</root>
考虑以下XSL:
<xsl:template match="root">
<xsl:apply-templates select="a | b | c"/> <!-- matches node 'b' with a non-mode template instead of the one with mode="test" -->
</xsl:template>
<xsl:template match="a">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="b">
<xsl:text> ignore </xsl:text>
</xsl:template>
<xsl:template match="b" mode="test">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="c">
<xsl:value-of select="."/>
</xsl:template>
我正在尝试编写一个XSL模板调用,该调用将根节点内的所有节点与其对应的模板匹配,但节点b
应与具有mode="test"
的模板匹配。不应该扰乱节点处理的顺序。
所需的输出是:
1
2
3
4
5
6
7
8
9
答案 0 :(得分:2)
我不知道这是否适用于您。而不是
<xsl:template match="root">
<xsl:apply-templates select="a | b | c"/>
</xsl:template>
DO
<xsl:template match="root">
<xsl:for-each select="*">
<xsl:choose>
<xsl:when test="name()='a'">
<xsl:apply-templates select="."/>
</xsl:when>
<xsl:when test="name()='b'">
<xsl:apply-templates select="." mode="test"/>
</xsl:when>
<xsl:when test="name()='c'">
<xsl:apply-templates select="."/>
</xsl:when>
</xsl:choose>
</xsl:for-each>
</xsl:template>
答案 1 :(得分:1)
我会定义一个新模式,然后根据需要重定向:
<xsl:template match="root">
<xsl:apply-templates select="a | b | c" mode="new"/>
</xsl:template>
<xsl:template match="a|c" mode="new">
<xsl:apply-templates select="."/>
</xsl:template>
<xsl:template match="b" mode="new">
<xsl:apply-templates select="." mode="test"/>
</xsl:template>
另一种解决方案是定义适用于多种模式的模板规则,因此a和c的“未命名模式”模板也适用于模式“new”,而b的mode =“test”模板也适用适用于“新”模式。 IIRC这需要XSLT 2.0(你没有说你正在使用哪个版本 - 请将来这样做。)