In this article, we will cover how to create a custom sitemap.xml in Episerver CMS without using any third-party DLLs.
We will also cover how to Exclude the Folder and Specific Page Type from the sitemap.xml
We will also cover how to Exclude Recycle bin from the sitemap.xml
Sitemap.cs
Create a Model named Sitemap.cs inside Models/Pages Folder.
using EPiServer.Core; using EPiServer.DataAbstraction; using EPiServer.DataAnnotations; namespace HpBlogs.Models.Pages { [ContentType(DisplayName = "Sitemap", GUID = "b3520c1e-9418-4485-a727-6e993ca19066", Description = "Sitemap XML")] public class Sitemap : PageData { } }
SitemapController.cs
Create a controller named SitemapController.cs and replace the existing code given below.
To search pages we will use EPiServer SearchClient Instance. Add all the missing references from the NuGet package.
using EPiServer.Web.Mvc; using HpBlogs.Models.Pages; using System.Web.Mvc; using System.Text; using EPiServer.ServiceLocation; using EPiServer; using EPiServer.Core; using EPiServer.Find.Framework; using EPiServer.Find; using System.Linq; using EPiServer.Find.Cms; using EPiServer.Web.Mvc.Html; namespace HpBlogs.Controllers { public class SitemapController : PageController<Sitemap> { public ActionResult Index(Sitemap sitemapPage) { StringBuilder sitemap = new StringBuilder(); sitemap.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sitemap.AppendLine("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"); var repository = ServiceLocator.Current.GetInstance<IContentLoader>(); var siteConfigFolder = repository.GetChildren<FolderPage>(ContentReference.RootPage).Where(x => x.Name.Equals("siteConfigFolder")).FirstOrDefault(); var sitemap_query = SearchClient.Instance.Search<PageData>() .Filter(x => (x.MatchTypeHierarchy(typeof(PageData))) // Fetch All Page Type only & !x.Ancestors().Match(siteConfigFolder.ContentLink.ID.ToString()) // Exculde all pages from specific folder & !x.ContentTypeName().Match("Trash") // Exculde all pages from Trash folder ).ExcludeDeleted(); // Here add all Page Type which you does not want to inculde in sitemap. sitemap_query = sitemap_query.Filter(x => !x.MatchTypeHierarchy(typeof(NewsDetails))); var sitemap_results = sitemap_query.Take(1000).GetContentResult(); sitemap_results.ToList().ForEach(fe => { sitemap.AppendLine("<url>"); sitemap.AppendLine("<loc>" + Url.ContentUrl(fe.ContentLink) + "</loc>"); sitemap.AppendLine("<lastmod>" + fe.SearchUpdateDate() + "</lastmod>"); sitemap.AppendLine("</url>"); }); sitemap.AppendLine("</urlset>"); return Content(sitemap.ToString(), "text/xml"); } } }
Login to Episerver CMS and Create a Sitemap Page in Root Folder.
Change the "Name in URL" from sitemap to sitemap.xml
>
Browse the Page to check all the listed pages in sitemap.xml
Post Comments(0)