2010-09-14

Building a google news sitemap with Rails and XML Builder

I was recently tasked with creating a google news sitemap for our main websites
See google's formatting instructions here:
http://www.google.com/support/news_pub/bin/answer.py?hl=en&answer=74288

This was my first time creating an xml output with rails/builder from scratch, so I'm documenting my experience.

oh yeah, this is an older rails app, version 2.0.2

I found a lot of documentation online about builder and creating the tags, but there is NO documentation anywhere about how to create tags with namespaces. I even looked through my massive collection of ebooks. NOTHING!

So I banged my head on my desk for a few hours(metaphorically), and stumbled upon the syntax by chance.

I really hope this helps someone in the future, because I would have paid actual money to someone for this information.

here's my rails {template}.xml.builder syntax I'm using to generate the proper google news sitemap:(sorry about the indenting, bloggers system screws up this post if I try to use the PRE tag to retain whitespace)



xml.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8"
xml.urlset "xmlns"=>"http://www.google.com/schemas/sitemap/0.9",
"xmlns:news"=>"http://www.google.com/schemas/sitemap-news/0.9" do
for a in @articles do
xml.url do
xml.loc(a.smart_permalink_url(true))
xml.news:news do
xml.news:publication do
xml.news(:name, $site[:name])
xml.news(:language, @lang)
end
xml.news(:genres, 'Blog')
xml.news(:publication_date, a.published_at.strftime("%Y-%m-%d"))
xml.news(:title, a.title)
xml.news(:keywords, a.keywords.gsub('_', ' '))
end
end
end
end