只是为了笑容,我想看看我是否可以在不使用<xsl:for-each>
的情况下在XSLT 1.0中重写Muenchian分组模板。 XML:
<jobs>
<job>
<year>2012</year>
<position>Mayonnaise Maker, Malden Mayonnaise Manufactory, Malden, MA</position>
</job>
<job>
<year>2012</year>
<position>Twine Twirler, Timmy's Twine, Tyngsboro, MA</position>
</job>
<job>
<year>2013</year>
<position>Bagel Boiler, Bob's Bagels, Boxboro, MA</position>
</job>
</jobs>
标准Muenchian解决方案,按年度分组:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="this-year" match="job" use="year"/>
<xsl:template match="jobs">
<resume>
<xsl:for-each select="job[count(. | key('this-year', year)[1]) = 1]">
<year y="{year}">
<xsl:for-each select="key('this-year', year)">
<position><xsl:value-of select="position"/></position>
</xsl:for-each>
</year>
</xsl:for-each>
</resume>
</xsl:template>
</xsl:stylesheet>
结果:
<?xml version="1.0"?>
<resume>
<year y="2012">
<position>Mayonnaise Maker, Malden Mayonnaise Manufactory, Malden, MA</position>
<position>Twine Twirler, Timmy's Twine, Tyngsboro, MA</position>
</year>
<year y="2013">
<position>Bagel Boiler, Bob's Bagels, Boxboro, MA</position>
</year>
</resume>
很容易摆脱外部<xsl:for-each>
。这有效:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="this-year" match="job" use="year"/>
<xsl:template match="jobs">
<resume>
<xsl:apply-templates select="job[count(. | key('this-year', year)[1]) = 1]"/>
</resume>
</xsl:template>
<xsl:template match="job">
<year y="{year}">
<xsl:for-each select="key('this-year', year)">
<position><xsl:value-of select="position"/></position>
</xsl:for-each>
</year>
</xsl:template>
</xsl:stylesheet>
但是......
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="this-year" match="job" use="year"/>
<xsl:template match="jobs">
<resume>
<xsl:apply-templates select="job[count(. | key('this-year', year)[1]) = 1]"/>
</resume>
</xsl:template>
<xsl:template match="job">
<year y="{year}">
<xsl:apply-templates select="key('this-year', year)"/>
</year>
</xsl:template>
<xsl:template match="key('this-year', year)">
<position><xsl:value-of select="position"/></position>
</xsl:template>
</xsl:stylesheet>
......没有:
error
xsltCompileIdKeyPattern : Literal expected
compilation error: file no-dice.xsl line 17 element template
xsltCompilePattern : failed to compile 'key('this-year', year)'
<xsl:template match="key('this-year', year)">
有效,但会抛出该错误。有没有办法将该密钥的处理推送到另一个模板?还是其他一些技巧可以让它发挥作用?
答案 0 :(得分:1)
使用模式:
<xsl:template match="job">
<year y="{year}">
<xsl:apply-templates select="key('this-year', year)" mode="group"/>
</year>
</xsl:template>
<xsl:template match="job" mode="group">
<position><xsl:value-of select="position"/></position>
</xsl:template>
当然,只要您只想复制position
元素,就可以使用
<xsl:template match="job">
<year y="{year}">
<xsl:copy-of select="key('this-year', year)/position"/>
</year>
</xsl:template>