How to update the lastmod date in your sitemap xml with Ant

Hmm, you want to add the “lastmod” node, but you’re too lazy to ever keep that up to date so you decide to update it with your Ant script whenever you deploy. Easy.

So you’ve just written a valid sitemap.xml file for your website because Google said it was a good idea. Great.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <url>
      <loc>http://www.stolencamerafinder.com/</loc>
      <lastmod>2011-04-21</lastmod>
      <changefreq>weekly</changefreq>
   </url>
</urlset>

First, you’ll need the jar for a third-party Ant task called XMLTask. Once you have that, the ant target you’ll need is simply:

<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask" classpath="test-lib/xmltask.jar"/>
<target name="update-sitemap" description="update the update date">
	<tstamp>
	    <format property="today" pattern="yyyy-MM-dd" locale="en,UK"/>
	</tstamp>
    <xmltask source="war/sitemap.xml" dest="war/sitemap.xml" standalone="yes" report="true">
        <replace path="/:urlset/:url/:lastmod/text()" withText="${today}"/>
    </xmltask>
</target>

Yeah yeah, this is kid’s stuff, why blog about it? Well, embarrassingly, it took me 3 hours of messing around to get it working. If I don’t write it down somewhere, I’ll only forget the next time I need to do this. Sigh.

Leave a Reply

Your email address will not be published. Required fields are marked *