我有一个 XML 文件,其中包含从 Internet 上的提要中读取的数据。 XML 是标准的 RSS 2.0 文件。看起来像(我省略了一些标签以缩短帖子):
<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<title/>
<item>
<title>Blah</title>
<category>CAT1</category>
</item>
<item>
<title>Blah2</title>
<category>CAT2</category>
</item>
<item>
<title>Blah3</title>
<category>CAT1</category>
</item>
</channel>
</rss>
我想做的是使用 XSLT 创建一个 HTML 文件。我的问题是我需要按 CATEGORY 标签对项目进行分组。为了生成类似的东西:
<div>
<span>CAT1</span>
<div>
<span>Blah</span>
<span>Blah3</span>
</div>
</div>
<div>
<span>CAT2</span>
<div>
<span>Blah2</span>
</div>
</div>
到目前为止,我发现了一堆教如何使用 XSLT 通过使用属性(如 this、this 和 this)进行分组的操作系统帖子。但是,我所有的适应尝试都失败了。
TIA,
鲍勃
最佳答案
这可以使用 Muenchian 分组法轻松解决。这个样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="byCategory" match="item" use="category" />
<xsl:template match="/">
<html><xsl:apply-templates /></html>
</xsl:template>
<xsl:template
match="item[generate-id()=generate-id(key('byCategory', category)[1])]">
<div>
<span><xsl:apply-templates select="category" /></span>
<xsl:apply-templates select="key('byCategory', category)"
mode="out" />
</div>
</xsl:template>
<xsl:template match="item"/>
<xsl:template match="item" mode="out">
<div><xsl:apply-templates select="title" /></div>
</xsl:template>
</xsl:stylesheet>
应用于此输入:
<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<title />
<item>
<title>Blah</title>
<category>CAT1</category>
</item>
<item>
<title>Blah2</title>
<category>CAT2</category>
</item>
<item>
<title>Blah3</title>
<category>CAT1</category>
</item>
</channel>
</rss>
产生:
<html>
<div>
<span>CAT1</span>
<div>Blah</div>
<div>Blah3</div>
</div>
<div>
<span>CAT2</span>
<div>Blah2</div>
</div>
</html>
关于xml - 如何使用 XSLT 对 RSS 提要进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6553069/