I originally wrote C# class because I couldn't find a simple class for dynamically creatingthe sitemap.xml file that google and other search engines like use to crawl your site. It was written some time ago for a previous website called eFood Order. and since then I have used it several times. I think its more relevant if I post it here though.
//Written By Luke Durrant //For www.efoodorder.com public class GSiteMap { private XmlTextWriter writer { get; set; } public GSiteMap(String xmlFile) { writer = new XmlTextWriter(xmlFile, System.Text.Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("urlset"); writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); writer.WriteAttributeString("xsi:schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"); writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"); WriteItem(new SiteMapItem { changefreq = ChangeFreq.always, loc = "http://www.efoodorder.com/", lastmod = DateTime.Now, priority = "1.0" }); WriteItem(new SiteMapItem { changefreq = ChangeFreq.monthly, loc = "http://www.efoodorder.com/Account/Register", lastmod = DateTime.Now, priority = "0.8" }); WriteItem(new SiteMapItem { changefreq = ChangeFreq.monthly, loc = "http://www.efoodorder.com/Feedback", lastmod = DateTime.Now, priority = "0.8" }); } public void WriteItem(SiteMapItem item) { writer.WriteStartElement("url"); writer.WriteElementString("loc", item.loc); writer.WriteElementString("changefreq", item.changefreq.ToString()); writer.WriteElementString("lastmod", TimeZone.CurrentTimeZone.ToUniversalTime(item.lastmod).ToString("s") + "+00:00"); writer.WriteElementString("priority", item.priority); writer.WriteEndElement(); // url } public void Finish() { writer.WriteEndElement(); // urlset writer.Close(); } } public class SiteMapItem { public String loc { get; set; } public ChangeFreq changefreq { get; set; } public DateTime lastmod { get; set; } public String priority { get; set; } } public enum ChangeFreq { always = 0, hourly = 1, daily = 2, weekly = 3, monthly = 4, yearly = 5, never = 6 }
Using it is quiet simple have a look below ( make sure you have read write access!)
GSiteMap sitemap = null; try { string SiteMapFile = @"~/sitemap.xml"; string xmlFile = Server.MapPath(SiteMapFile); sitemap = new GSiteMap(xmlFile); List list = null; //Create your list of items here //Then just loop through them foreach (SiteMapItem item in list) { sitemap.WriteItem(item); } } catch (Exception up) { throw up; } finally { sitemap.Finish(); }