【问题标题】:XSL Most commonXSL 最常见
【发布时间】:2013-12-23 14:52:02
【问题描述】:

您好,我是 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 Friedman,因为他写了 2 篇文章,而其他人只写了一篇。我敢肯定这可能很容易,但正如我所说,我对这一切都很陌生,我似乎无法管理它。在 for-each 循环和排序和计数之间,我头晕目眩。

感谢各位,我正在上大学,我准备在期末考试中以某种形式提出这样的问题。干杯!

【问题讨论】:

  • 您能否用您尝试过的方法、您使用的处理器以及您使用的 XSLT 版本来更新您的问题?否则,对于基本概念,您需要查找 XSLT 1.0 的 Muenchian 方法和 XSLT 2.0 的 for-each-group。

标签: xml xslt


【解决方案1】:

这里最有用的策略可能是

  1. 定义一个为您提供给定作者姓名的所有故事
  2. 按其键值匹配数的降序对作者列表进行排序
  3. 只取该列表的第一个元素

键定义超出所有模板:

<xsl:key name="storiesByAuthor" match="story" use="author" />

然后要按故事数量排序并获取第一个元素,您需要在 XSLT 1.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>

这个 for-each 产生重复的事实在这里不是问题,因为您只关心第一次“迭代”。如果您有多个作者具有相同的最大故事数,您将获得原始文档中首先提到的那个(因为xsl:sort 是“稳定的”,即具有相同排序键值的项目按文档顺序返回)。

对于 XSLT 2.0,您可以使用 xsl:perform-sort 而不是 for-each,但鉴于您使用的是 &lt;?xml-stylesheet?&gt;,我认为您是在浏览器中进行转换,并且大多数(全部?)浏览器仅支持 1.0 .

【讨论】:

  • +1 同样在 XSLT 2.0 中,OP 可以使用 distinct-values()。不过,我认为您对 1.0 的看法是正确的 (&lt;?xml-stylesheet?&gt;)。
猜你喜欢
  • 1970-01-01
  • 2016-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-21
  • 2021-02-06
相关资源
最近更新 更多