动态创建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));   
} 

你可能感兴趣的:(xml,Web)