Friday, June 4, 2010

Google Sitemap with Asp.Net C#

Step 1: Get a Google account
Step 2: Login to http://www.google.com/webmasters/sitemaps
Step 3: Add a website
Step 4: Verify that you are the owner by uploading an HTML file or add a Meta tag
Step 5: Add a sitemap for that website

Class will be as follows :

using System;
using System.Xml;

namespace shop.BLL.Utility
{
    public class SiteMapFeedGenerator
    {
        XmlTextWriter writer;

        public SiteMapFeedGenerator(System.IO.Stream stream, System.Text.Encoding encoding)
        {
            writer = new XmlTextWriter(stream, encoding);
            writer.Formatting = Formatting.Indented;
        }

        public SiteMapFeedGenerator(System.IO.TextWriter w)
        {
            writer = new XmlTextWriter(w);
            writer.Formatting = Formatting.Indented;
        }
        /// 

        /// Writes the beginning of the SiteMap document
        /// 
        public void WriteStartDocument()
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("urlset");

            writer.WriteAttributeString("xmlns", "http://www.google.com/schemas/sitemap/0.84");
        }

        /// 
        /// Writes the end of the SiteMap document
        /// 
        public void WriteEndDocument()
        {
            writer.WriteEndElement();
            writer.WriteEndDocument();
        }

        /// 

        /// Closes this stream and the underlying stream
        /// 
        public void Close()
        {
            writer.Flush();
            writer.Close();
        }

        public void WriteItem(string link, DateTime publishedDate, string priority)
        {
            writer.WriteStartElement("url");
            writer.WriteElementString("loc", link);
            writer.WriteElementString("lastmod", publishedDate.ToString("yyyy-MM-dd"));
            writer.WriteElementString("changefreq", "always");
            writer.WriteElementString("priority", priority);
            writer.WriteEndElement();
        }
    }
}

 


This is just a basic Google Sitemap, you can add elements for geographic info about the item or mobile sitemaps etc. You can find more info for that on:  http://www.google.com/support/webmasters/bin/answer.py?answer=34657


You can use this class in an .aspx or .ashx file. I used an .aspx in the following (code behind) sample:


protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();
        Response.ContentType = "text/xml";
        shop.BLL.Utility.SiteMapFeedGenerator gen = new shop.BLL.Utility.SiteMapFeedGenerator(Response.Output);
        
        gen.WriteStartDocument();
        gen.WriteItem("http://www.mysamplesiterocks.com/Default.aspx", DateTime.Now, "1.0");
 gen.WriteEndDocument();
        gen.Close(); 
    }