Generate Sitemap.xml with Sitecore

This blog will give a small demo about how to create customized solution in Sitecore. We will be creating a sitemap.xml in this blog.

In sitecore, request are served through pipelines and 1st pipeline is “httpRequestBegin“.

This pipeline is having many processors in it. If any new request comes, there are steps which will create the complete request. (for more detail about different pipeline, Click Here )

Here, the request will traverse through the specified processors to create the result of the request.

Follow the steps to generate sitemap.xml:

Step 1: Create Sitecore content tree structure for the site. This structure could be different with Sitemap.
sitemapcontenttree

Step 2: Create Processor for HttpRequestBegin pipeline,

File: UrlSet.cs (Model)


using System.Collections.Generic;
using System.Xml.Serialization;

namespace Sitemap.Models
{
    ///
<summary>
    /// Class to generate urlset for sitemap
    /// </summary>

    [XmlRoot("urlset")]
    public class Urlset
    {
        ///
<summary>
        /// Constructor to initialize Url Object
        /// </summary>

        public Urlset() { Url = new List<Url>(); }

        ///
<summary>
        /// Urls collection
        /// </summary>

        [XmlElement("url")]
        public List<Url> Url { get; set; }

    }

    ///
<summary>
    /// Class to generate url with its parameters for sitemap
    /// </summary>

    public class Url
    {
        ///
<summary>
        /// Location Parameter
        /// </summary>

        [XmlElement("loc")]
        public string Loc { get; set; }

        ///
<summary>
        /// Last modified on
        /// </summary>

        [XmlElement("lastmod")]
        public string Lastmod { get; set; }

        //Add required properties here like changefreq, priority
    }
}

Filename: Sitemap.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
using Sitecore;
using Sitecore.Diagnostics;
using Sitecore.Links;
using Sitecore.Pipelines.HttpRequest;
using Sitemap.Models;

namespace Sitemap.Pipelines.HTTPRequestBegin
{
    public class Sitemap : HttpRequestProcessor
    {
        public override void Process(HttpRequestArgs args)
        {
            if (!System.IO.File.Exists(args.Context.Request.PhysicalPath) &&
                !System.IO.Directory.Exists(args.Context.Request.PhysicalPath))
            {
                Assert.ArgumentNotNull(args, "args");
                if (args.Url == null || !args.Url.FilePath.ToLower().EndsWith("sitemap.xml")) return;
                try
                {
                    // Homepage of the Website.
                    // Start path will give homepage including Multisite.

                    var homepage = Context.Database.GetItem(args.StartPath);
                    var ser = new XmlSerializer(typeof(Urlset));

                    var urlSet = new Urlset();

                    //Create node of Homepage in Sitemap.
                    var tmpurlset = new List<Url>
                    {
                        new Url
                        {
                            Loc = GetAbsoluteLink(LinkManager.GetItemUrl(homepage)),
                            Lastmod = homepage.Statistics.Updated.ToString("yyyy-MM-dd hh:mm:ss")
                        }
                    };

                    // Get all decendants of Homepage to create full Sitemap.
                    var childrens = homepage.Axes.GetDescendants();

                    tmpurlset.AddRange(childrens.Select(childItem => new Url
                    {
                        Loc = GetAbsoluteLink(LinkManager.GetItemUrl(childItem)), Lastmod = childItem.Statistics.Updated.ToString("yyyy-MM-dd hh:mm:ss")
                    }));

                    // Populate created collection to right object
                    urlSet.Url = tmpurlset;

                    //Write XML Response for Sitemap.
                    var response = HttpContext.Current.Response;
                    response.AddHeader("Content-Type", "text/xml");
                    ser.Serialize(response.OutputStream, urlSet);
                    HttpContext.Current.Response.End();
                    //Response Ends Here
                }
                catch (Exception ex)
                {
                    Log.Error("Error - Sitemap.xml.", ex);
                }
            }
        }

        public static string GetAbsoluteLink(string relativeUrl)
        {
            return HttpContext.Current.Request.Url.Scheme + "//" + HttpContext.Current.Request.Url.Host + relativeUrl;
        }
    }
}

Step 3: Create new config like “sitemap.config” at like “\Website\App_Config\Include\z_custom\”. Content will be as below.

<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <httpRequestBegin>
        <processor           patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel']"           type="Sitemap.Pipelines.HTTPRequestBegin.Sitemap, VShared.Sitemap">
        </processor>
      </httpRequestBegin>

      <preprocessRequest>
        <processor patch:instead="processor[@type='Sitecore.Pipelines.PreprocessRequest.FilterUrlExtensions, Sitecore.Kernel']" type="Sitecore.Pipelines.PreprocessRequest.FilterUrlExtensions, Sitecore.Kernel">
          <param desc="Allowed extensions (comma separated)">aspx, ashx, asmx, xml</param>
          <param desc="Blocked extensions (comma separated)">*</param>
          <param desc="Blocked extensions that stream files (comma separated)">*</param>
          <param desc="Blocked extensions that do not stream files (comma separated)"></param>
        </processor>
      </preprocessRequest>
    </pipelines>
  </sitecore>
</configuration>

All done now, Here is the result:

SitemapResult

So,

  • sitemap.xml will be generate on request and so actual file not required to be saved on the server or anywhere.
  • sitemap.xml will be generated from any page even if user is on any child page.
  • This supports in MVC and WebForm both.
  • This supports Multilingual as well.

Link of Sitecore marketplace module ready to use is here.

 

Cheers for now.

Advertisements

2 thoughts on “Generate Sitemap.xml with Sitecore

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: