Tuesday, March 29, 2011

RSS Feed Parser/Reader

def rssurl = "http://feeds.digg.com/digg/news/popular.rss"  
def slurp = new XmlSlurper()  
def rssObj = slurp.parse(rssurl).declareNamespace(digg: "http://digg.com/docs/diggrss/", media: "http://search.yahoo.com/mrss/")  

rssObj.channel.item.eachWithIndex { item , num ->  
    println "-------------------------------------------"  
    println "#${num + 1}: ${item.title}"
    println item."digg:category"  
    def url = item."media:thumbnail".@url.text()  
    if ( url ) {  
        println url  
        download(num, url)  
    }  
}  

def download(num , address)  
{  
    def filename =  address.tokenize("/")[-2]  
    def tmp = address.tokenize("/")[-1]   
    def ext = tmp.tokenize(".")[-1]  
    filename = filename << "." << ext  
    println "saving image file : " << filename  
    def file = new FileOutputStream(filename.toString())  
    def out = new BufferedOutputStream(file)  
    out << new URL(address).openStream()  
    out.close()  
}

println "-------------------------------------------\ndone"

http://groovyconsole.appspot.com/script/451002

No comments:

Post a Comment