嗨,我是XSL新手,我正在尝试创建一个XSL样式表,以便根据他们所写文章的数量(如XML文档中所指定的)打印最常见作者的姓名。
XML
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="busiestAuthor.xsl"?>
<latestIssue>
<issue number="357" />
<date>
<day> 4 </day>
<month> 1 </month>
<year> 2013 </year>
</date>
<stories>
<story>
<title> The earth is flat </title>
<author> Tom Friedman </author>
<url> http://www.HotStuff.ie/stories/story133456.xml </url>
</story>
<story>
<title> Films to watch out for in 2013 </title>
<author> Brated Film Critic </author>
<url> http://www.HotStuff.ie/stories/story133457.xml </url>
</story>
<story>
<title> The state of the economy </title>
<author> Tom Friedman </author>
<url> http://www.HotStuff.ie/stories/story133458.xml </url>
</story>
<story>
<title> Will an asteroid strike earth this year? </title>
<author> Stargazer </author>
<url> http://www.HotStuff.ie/stories/story133459.xml </url>
</story>
</stories>
</latestIssue>所以我希望busiestAuthor.xsl打印的结果就是Tom ,因为他写了两篇文章,其他人只写了一篇。我相信这可能很容易,但正如我所说,我对这一切都是新手,我似乎无法做到这一点。在每一个循环、分类和计数之间,我的头在旋转。
非常感谢,伙计们,我正在大学学习,这样的问题可能会在期末考试中以某种形式出现。干杯!
发布于 2013-12-23 16:59:47
这里最有用的策略可能是
键定义超出了所有模板:
<xsl:key name="storiesByAuthor" match="story" use="author" />然后,要按故事数量进行排序并使用第一个元素,您需要在XSLT1.0中执行类似的操作:
<xsl:for-each select="/latestIssue/stories/story/author">
<xsl:sort select="count(key('storiesByAuthor', .))"
data-type="number" order="descending" />
<xsl:if test="position() = 1">
<!-- in here, . is one of the author elements for the author with the
most stories -->
</xsl:if>
</xsl:for-each>这对于-每个生成重复并不是一个问题,因为你只关心第一个“迭代”。如果您有多个作者具有相同的最大故事数,您将得到原始文档中第一个提到的故事(因为xsl:sort是“稳定的”,即具有相同排序键值的项按文档顺序返回)。
对于XSLT2.0,您可以使用xsl:perform-sort而不是for-each,但考虑到您使用的是<?xml-stylesheet?>,我假设您是在浏览器中进行转换,而且大多数(全部?)浏览器只支持1.0。
https://stackoverflow.com/questions/20745893
复制相似问题