xml - 如何使用 XSLT 对 RSS 提要进行分组

标签 xml xslt rss

我有一个 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 通过使用属性(如 thisthisthis)进行分组的操作系统帖子。但是,我所有的适应尝试都失败了。

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/

相关文章:

xml - Scala 填充模板的方式?

xslt - 是否可以仅使用 XSLT 创建 "two step view"

java - 使用 Rome 的有效 RSS 2.0

c# - 从字符串中剥离 WordML

java - 如何在Spring Integration中获取rss feedChannel SyndEntry消息的来源?

android - 理解 Android XML layout_weight 的问题

php - 使用 simplexml_load_string() 将 XML 转换为 JSON 时如何删除 "@attributes"

javascript - 使用 JavaScript 修改加载的 XML(通过 XSL 在浏览器(Chrome)中显示)

xml - 使用输入 xsd 架构验证 XSL 文档选择和匹配属性

regex - XSLT - 检查元素字符串中是否存在模式