【blog】SpringMVC返回RSS格式的XML数据

时间:2023-01-11 01:11:32

代码

import com.sun.syndication.feed.rss.Channel;
import com.sun.syndication.feed.rss.Content;
import com.sun.syndication.feed.rss.Description;
import com.sun.syndication.feed.rss.Item;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.WireFeedOutput;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Author:Mr.X
 * Date:2017/11/12 14:01
 * Description:
 */
public class RSSUtil {

    public static String channleItemXml() {
        Date date = new Date();

        Channel channel = new Channel("rss_2.0"); // 该type参数为固定格式
        channel.setTitle("test rome channel title");
        channel.setDescription("channel的描述");
        channel.setLink("http://hi.baidu.com/openj/rss");
        channel.setPubDate(date);
        channel.setEncoding("GBK");

        List items = new ArrayList();
        Item item = new Item();
        item.setAuthor("zhangwei");
        item.setTitle("item title");

        Description desc = new Description();
        desc.setType("item desc type");
        desc.setValue("item desc value");
        item.setDescription(desc);

        items.add(item);// 添加一个item

        Item item2 = new Item();
        item2.setAuthor("zhangwei");
        item2.setTitle("use rome to read rss");

        Description desc2 = new Description();
        desc2.setValue("you must import rome_1.0.jar & jdom.jar");
        item2.setDescription(desc2);
        Content content = new Content();
        content.setValue("rome是用来发布读取rss的工具,遵循rss标准的XML");
        item2.setContent(content);

        items.add(item2);// 添加一个item

        channel.setItems(items);

        WireFeedOutput out = new WireFeedOutput();
        String str = "";
        try {
            str = out.outputString(channel);
        } catch (FeedException ex) {
            ex.printStackTrace();
        }
        return str;
    }

    public static void main(String[] args) {
        System.out.println(channleItemXml());
    }
}
@GetMapping(value = "feed", produces = "application/xml")
@ResponseBody
public String feed() {
    return RSSUtil.channleItemXml();
}

效果

【blog】SpringMVC返回RSS格式的XML数据