有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

xml-Java:将RSS提要转换为HTML

我目前正在做一个java项目,在那里我得到一个包含RSS提要的url,需要将RSS提要转换成HTML。因此,我做了一些研究,并设法将其转换为XML,以便使用XSLT将其转换为HTML。但是,该过程需要一个XSL文件,我不知道如何获取/创建该文件。我将如何着手解决这个问题?我无法硬编码,因为资源url可能会更改站点上的事件/新闻,从而影响我的输出


共 (1) 个答案

  1. # 1 楼答案

    RSS提要有两种格式:RSS 2.0ATOM——根据您想要/需要处理哪种类型,您将需要不同的XSLT

    这是一个非常简单的XSLT,可以将RSS 2.0提要转换为HTML页面:

    <xsl:stylesheet 
      version="1.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:output method="html" indent="yes"/>
    
      <xsl:template match="text()"></xsl:template>
    
      <xsl:template match="item">
        <h2>
          <a href="{link}">
            <xsl:value-of select="title"/>
          </a>
        </h2>
        <p>
          <xsl:value-of select="description" disable-output-escaping="yes"/>
        </p>
      </xsl:template>
      <xsl:template match="/rss/channel">
        <html>
          <head>
            <title>
              <xsl:value-of select="title"/>
            </title>
          </head>
        </html>
        <body>
          <h1>
            <a href="{link}">
              <xsl:value-of select="title"/>
            </a>
          </h1>
          <xsl:apply-templates/>
        </body>
      </xsl:template>
    
    </xsl:stylesheet>
    

    。。。这对于ATOM提要也是一样的:

    <xsl:stylesheet 
      version="1.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:atom="http://www.w3.org/2005/Atom">
    
      <xsl:output method="html" indent="yes"/>
    
      <xsl:template match="text()"></xsl:template>
    
      <xsl:template match="atom:entry">
        <h2>
          <a href="{atom:link/@href}">
            <xsl:value-of select="atom:title"/>
          </a>
        </h2>
        <p>
          <xsl:value-of select="atom:summary"/>
        </p>
      </xsl:template>
    
      <xsl:template match="/atom:feed">
        <html>
          <head>
            <title>
              <xsl:value-of select="atom:title"/>
            </title>
          </head>
        </html>
        <body>
          <h1>
            <a href="{atom:link/@href}">
              <xsl:value-of select="atom:title"/>
            </a>
          </h1>
          <xsl:apply-templates/>
        </body>
      </xsl:template>
    
    </xsl:stylesheet>