RSS Feed autodiscovery.

使用一些浏览器的浏览某个页面时会提示你这个页面有那些Rss源。她时怎样做的呢??

不过是在HTML里的<head>部分里加一行代码,类似:

<link rel="alternate" type="application/rss+xml" title="Default RSS1.0 feed" <br="">href=" http://www.zhangyining.net/weblog/rss/rss.pl"/>

这行代码的作用就是告诉访问该页面的客户端程序(浏览器,RSS Reader,或者是RSS聚合
器)该页面提供RSS Feed以及该Feed的地址,这样,客户端程序可以直接反馈给用户提示用
户可以订阅的内容(例子:桌面或者基于浏览器的RSS Reader),或者自动聚合内容(例子
:RSS 搜索引擎)。

Ok。 我用java实现这一功能。代码如下。。需要nekohtml-0.9.5.jar 和 xercesImple-2.6.2.jar

    /**
     * This function is Feed Autodiscovery, You just need passing the url, It would
     * return the feeds.
     *
     * Rule,  gets the elements "<linke>", check the type attribute whether is rss-xml type,
     * if true, get the href attribute.
     *
     * @param url   the page url that need to discovery
     * @return      Feed list
     */
    public static List<string> discoveryFeedList(String url){
        List<string> rt = new ArrayList<string>();
        if (StringUtils.isBlank(url)){
            return rt;
        }
       
        DOMParser parser = new DOMParser();
        try {
            parser.parse(url);
        }catch(Exception e){
            // ignore the exception; just return empty value;
            return rt;
        }
        NodeList list = parser.getDocument().getElementsByTagName("link");
        for(int i=0; i<list.getlength(); i++){<br="">            Node node = list.item(i);
            String rssurl = getRssUrl(node, url);
            if (StringUtils.isNotBlank(rssurl)){
                rt.add(rssurl);
            }
        }
        return rt;
    }
   
    /**
     * dig rss url.
     * @param node
     * @return    URL,  if not found, return null.
     */
    private static String getRssUrl(Node node, String url){
        if (node == null || node.getAttributes().getLength() == 0){
            return null;
        }
        // Map<attriname, attrivalue="">
        Map<string, string=""> attriMap = new HashMap<string, string="">();
        for(int i=0; i<node.getattributes().getlength(); i++){<br="">            attriMap.put(node.getAttributes().item(i).getNodeName(), node
                    .getAttributes().item(i).getNodeValue());
           
        }
        String type = attriMap.get("type");
        if (!StringUtils.isBlank(type)
                && (type.equalsIgnoreCase("application/rss+xml") ||
                        type.equalsIgnoreCase("application/atom+xml"))) {
            String href = attriMap.get("href");
            if (!StringUtils.isBlank(href) && href.toLowerCase().startsWith("http")){
                return href;
            }else{
                return url.trim().endsWith("/") ? url + href : url + "/" + href;
            }
        }
        return null;
    }

你可能感兴趣的:(html,.net,xml,浏览器,搜索引擎)