There are time when you are going to deploy your
website on production and client want Sitemap file of website. Sitemap file is
used to improve SEO results.
Sometimes client have some weird requirement that
create XML sitemap dynamically for Sitecore website.
For this type of requirement, always keep one field
"Show Sitemap" in all the page content.
Here is a code to generate sitemap dynamically.
Remember you need a permission to update Sitemap.xml file on server.
public bool GenerateXml(List<Tuple<string, string, string>> lstTuples)
//generateXml
{
bool result = false;
string xmlFile = HttpContext.Current.Server.MapPath("/Sitemap.xml");
XmlTextWriter writer = new XmlTextWriter(xmlFile, System.Text.Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
{
writer.WriteStartElement("urlset");
writer.WriteAttributeString("xmlns:xhtml", "http://www.w3.org/1999/xhtml");
writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
string url = "http://" + System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
foreach (var value in lstTuples)
{
writer.WriteStartElement("url");
writer.WriteElementString("loc",
System.Web.HttpUtility.HtmlEncode(url
+ value.Item2));
writer.WriteElementString("lastmod", value.Item3);
writer.WriteElementString("changefreq", "weekly");
writer.WriteElementString("priority", "0.5");
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
result = true;
}
return result;
}
Pass the Tuple collection which contains URL and last
modified date of content items.
This code should create file with below data
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://test/</loc>
<lastmod>2015-04-06</lastmod>
<changefreq>weekly</changefreq>
<priority>0.5</priority>
</url>
<url>
<lastmod>2015-03-23</lastmod>
<changefreq>weekly</changefreq>
<priority>0.5</priority>
</url>
Please leave your comments or share this code if it’s
useful for you.