XSLT professional site
  首 页 经典书籍 精彩实例 热门文章 语法详解 休闲天地  
题目:

用XSL解析RSS,生成html形式的流,输出到前台
实现:

try {
//取得xml和xsl流
StreamSource source = new StreamSource(urlRSS);
StreamSource style = new StreamSource("titleList.xsl");
//设置返回响应类型和字符集
response.addHeader("Content-Type","text/html; charset=UTF-8");
//设置输出流,把生成的结果传送到输出流中。构造函数中的输出流也可以是其他形式。
result = new StreamResult(response.getWriter());
//初始化转换器
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer(style);
//设置生成html形式结果流的编码为UTF-8
transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
//设置html形式的流是有缩进格式的
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
//转换并且输出流
transformer.transform(source,result);
} catch(Exception e) {
e.printStackTrace();
}
titleList.xsl源文件:
< xml version="1.0" encoding="UTF-8" >
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<xsl:apply-templates select="//channel"/>
<ul>
<xsl:apply-templates select="//item"/>
</ul>
</xsl:template>
<xsl:template match="channel">
<xsl:apply-templates select="img"/>
<h2><xsl:value-of select="title"/></h2>
<h3><xsl:value-of select="description"/></h3>
</xsl:template>
<xsl:template match="item">
<li>
<xsl:element name="a">
<xsl:attribute name="href"><xsl:value-of select="link"/></xsl:attribute>
<xsl:value-of select="title"/>
</xsl:element>
<br/>
<xsl:element name="font">
<xsl:attribute name="color">#AA5522</xsl:attribute>发表时间:
<xsl:value-of select="pubDate"/>
</xsl:element>
<p><xsl:value-of disable-output-escaping="yes" select="description"/></p>
</li>
</xsl:template>
</xsl:stylesheet>
<上一篇    下一篇>
Email: xslt.org.cn@gmail.com

© 2007     xslt.org.cn