Skip to content

Instantly share code, notes, and snippets.

@DanDiplo
Created May 31, 2015 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanDiplo/fabbb8be5521c9286f82 to your computer and use it in GitHub Desktop.
Save DanDiplo/fabbb8be5521c9286f82 to your computer and use it in GitHub Desktop.
<%@ WebHandler Language="C#" Class="Sitemap" %>
using System;
using System.Web;
using System.Linq;
using System.Collections.Generic;
using System.Xml.Linq;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Web;
public class Sitemap : IHttpHandler
{
/* Generates an XML Sitemap for Umbraco using LinqToXml */
private static readonly XNamespace xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";
public void ProcessRequest(HttpContext context)
{
// Set correct headers from XML
context.Response.ContentType = "text/xml";
context.Response.Charset = "utf-8";
// Get the absolute base URL for this website
Uri url = HttpContext.Current.Request.Url;
string baseUrl = String.Format("{0}://{1}{2}",
url.Scheme, url.Host, url.IsDefaultPort ? String.Empty : ":" + url.Port);
// Create a new XDocument using namespace and add root element
XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
XElement urlset = new XElement(xmlns + "urlset");
UmbracoHelper umbHelper = new UmbracoHelper(UmbracoContext.Current);
// Get the root no
var rootNodes = umbHelper.TypedContentAtRoot().Where(n => n.TemplateId > 0);
// Iterate all nodes in site and add them to document
RecurseNodes(urlset, rootNodes, baseUrl);
doc.Add(urlset);
// Write XML document to response stream
context.Response.Write(doc.Declaration + "\n");
context.Response.Write(doc.ToString());
}
// Method to recurse all nodes and create each element
private static void RecurseNodes(XElement urlset, IEnumerable<IPublishedContent> nodes, string baseUrl)
{
foreach (IPublishedContent n in nodes)
{
if (n.TemplateId > 0)
{
string url = n.UrlAbsolute();
if (!url.StartsWith("http"))
{
url = baseUrl + url;
}
// Create the XML node
XElement urlNode = new XElement(xmlns + "url",
new XElement(xmlns + "loc", url),
new XElement(xmlns + "lastmod", n.UpdateDate.ToUniversalTime()));
urlset.Add(urlNode);
}
// Check if the node has any child nodes and, if it has, recurse them
if (n.Children() != null)
{
RecurseNodes(urlset, n.Children(), baseUrl);
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment