Site Map is used to tell about your web site and its content to various search engines like Google, Yahoo...etc. By using Site Map search engine index your web site pages based on quality of your content.
Here we discuss about how to create site map in asp.net by using C#. First we need to remove the all html content from aspx page and change rendering format to XML from text because site map should be in XML format only as shown below.
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Xml" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "text/xml";
string strPath = string.Empty;
string strDate = string.Empty;
strPath = "http://localhost/";//your web site address
strDate = DateTime.Now.Year + "-" + ((DateTime.Now.Month.ToString().Length == 1) ? ("0" + DateTime.Now.Month.ToString()) : DateTime.Now.Month.ToString()) + "-" + ((DateTime.Now.Day.ToString().Length == 1) ? ("0" + DateTime.Now.Day.ToString()) : DateTime.Now.Day.ToString());
using (XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8))
{
writer.WriteStartDocument();
writer.WriteStartElement("urlset");
writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
writer.WriteStartElement("url");
writer.WriteElementString("loc", strPath + "Default.aspx");
writer.WriteElementString("lastmod", strDate);
writer.WriteElementString("changefreq", "Daily");
writer.WriteElementString("priority", "1");
writer.WriteEndElement();
writer.WriteStartElement("url");
writer.WriteElementString("loc", strPath + "Default2.aspx");
writer.WriteElementString("lastmod", strDate);
writer.WriteElementString("changefreq", "Daily");
writer.WriteElementString("priority", "1");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
}
Response.End();
}
</script>
As shown above we are rendering the output as XML format by using
Response.Clear();
Response.ContentType = "text/xml";
We are forming the XML output by using XmlTextWriter class which is available in System.Xml namespace. The root element of the site map is urlset and sub element should be url for each page. url contains various other elements like loc(represents the location of the page), lastmod(represents the last modified date), changefreq(how frequently your page content change) and priority(priority of the page).
The output of the site map is shown below.