0

假设我有一个这样的 XML 文档:

<library xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="library.xsd">
<book>
    <title>Harry Potter Sorcerer's Stone</title>
    <artist>J.K. Rowling</artist>
</book>
<book>
    <title>Harry Potter Chamber of Secrets</title>
    <artist>J.K. Rowling</artist>
</book>
<book>
    <title>Harry Potter Prisoner of Azkaban</title>
    <artist>J.K. Rowling</artist>
</book>     
</library>

我希望我的 XSLT 文档在标题中找到 3 个最常用的单词,以及它们的数量。(所以我想输出:“Harry”:3,“Potter”:3,“of”:2)。

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<h2>3 Most Commonly Used Words</h2>
<ul>
   <li>Word - Count</li>
</ul>
</xsl:template>
</xsl:stylesheet>

我是一个 XML 初学者,不清楚如何使用 XSLT 和 XPath 进行聚合。我在想 tokenize() 和 sum() 的某种组合?有人可以指出我正确的方向吗?

4

1 回答 1

2
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output indent="yes"/>
    <xsl:template match="/">
        <h2>3 Most Commonly Used Words</h2>
        <ul>
        <xsl:for-each-group group-by="." select="
            for $w in //title/tokenize(., '\W+') return $w">
            <xsl:sort select="count(current-group())" order="descending" />
            <xsl:if test="position() lt 4">
                <li>
                    <xsl:value-of select="current-grouping-key()"/>
                    <xsl:text> - </xsl:text>
                    <xsl:value-of select="count(current-group())"/>
                </li>
            </xsl:if>
        </xsl:for-each-group>
        </ul>
    </xsl:template>
</xsl:stylesheet>
于 2013-11-05T01:07:58.467 回答