我想使用apply-templates将一些模板应用到我的xml,但我似乎无法确定如何为每个"数据类型"设置多个模板类型。 例如,使用此xml:
<?xml version="1.0" encoding="UTF-8"?>
<items>
<item name='1'>
first
</item>
<item name='2'>
second
</item>
<item name='3'>
third
</item>
</items>
我使用以下xslt来获取我想要的输出:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" encoding="UTF-8" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
<xsl:template match="items/item">
<xsl:value-of select='.'></xsl:value-of>
</xsl:template>
<xsl:template match="/">
<html>
<body>
<font color="blue">
<xsl:apply-templates select="items/item[@name='1']"></xsl:apply-templates>
</font>
<font color="red">
<xsl:apply-templates select="items/item[@name='1']"></xsl:apply-templates>
</font>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
是:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body><font color="blue">
first
</font><font color="red">
first
</font></body>
</html>
第一项为蓝色,后面是同一项红色。但是有了这个,我仍然会得到很多切割粘贴样板,我很乐意进入模板&#34; items / item&#34;但是我无法弄清楚如何获得选择两种颜色之一的相同模板。有没有办法在上面的代码中用包装器做到这一点?
答案 0 :(得分:2)
这个问题非常相似,但也许不那么明确:
XSL apply more than one template
如果您使用&#34;模式&#34;在xsl:template中的属性,您可以使用相同的select属性专门化模板:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" encoding="UTF-8" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
<xsl:template match="items/item" mode="blue">
<font color="blue"><xsl:value-of select='.'></xsl:value-of></font>
</xsl:template>
<xsl:template match="items/item" mode="red">
<font color="red"><xsl:value-of select='.'></xsl:value-of></font>
</xsl:template>
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates select="items/item[@name='1']" mode="blue"></xsl:apply-templates>
<xsl:apply-templates select="items/item[@name='1']" mode="red"></xsl:apply-templates>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
这应该允许您将红色和蓝色字体包装器移动到模板定义中,并允许您根据模式属性选择它们。