动态创建RSS文档

这里需要Jdom的API

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.XMLOutputter;
/**
* 动态创建RSS文档
* @author 李英夫(09.06.25)
*/
public class RssHandle {
/**
* RSS2.0版
* item:所有item元素的集合,集合的每个元素为String[],长度为3,分别保存item下必有的三个元素title,link,description<br/>
* from:为长度为三的字符串数组,分别保存channel下必有的三个元素title,link,description<br/>
* path:文件保存路径
* @param item
* @param from
* @param path
* @throws IOException
* @throws JDOMException
*/
public static void createRSSXml(List<String[]> items,String[] from, String path) throws IOException, JDOMException{
/**
* RSS文档的结构是:
* <?xml version="1.0" encoding="ISO-8859-1" ?>
* <rss version="2.0">
* <channel>
* <title>W3School Home Page</title>
* <link>http://www.w3school.com.cn</link>
* <description>Free web building tutorials</description>
* <item>
* <title>RSS Tutorial</title>
* <link>http://www.w3school.com.cn/rss</link>
* <description>New RSS tutorial on W3School</description>
* </item>
* <item>
* <title>XML Tutorial</title>
* <link>http://www.w3school.com.cn/xml</link>
* <description>New XML tutorial on W3School</description>
* </item>
* </channel>
* </rss>
* 其中<rss>为根元素
* <channel>为频道,必有且只能有一个
* 其子元素<title><link><description>必有
* <item>可以有多个代表内容
* 其子元素<title><link><description>必有
*/
Element rss = new Element("rss");//根元素rss
rss.setAttribute("version", "2.0");//RSS2.0版
Document rssXml = new Document(rss);//创建RSS文档
Element channel = new Element("channel");//<channel>

//在channel下分别添加title,link,description
channel.addContent(new Element("title").setText(from[0]));
channel.addContent(new Element("link").setText(from[1]));
channel.addContent(new Element("description").setText(from[2]));

//将所有的item遍历出来
Iterator<String[]> it = items.iterator();
while (it.hasNext()) {
String[] strings = (String[]) it.next();
Element item = new Element("item");
item.addContent(new Element("title").setText(strings[0]));
item.addContent(new Element("link").setText(strings[1]));
item.addContent(new Element("description").setText(strings[2]));
channel.addContent(item);
}

//将channel添加到rss根元素下
rss.addContent(channel);
// 输出xml 文件;
Format format=Format.getPrettyFormat(); //格式化文档
format.setEncoding("gbk"); //由于默认的编码是utf-8,中文将显示为乱码,所以设为gbk
XMLOutputter xOutputter = new XMLOutputter();
xOutputter.setFormat(format);
xOutputter.output(rssXml, new FileOutputStream(path));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值