Xml Sitemap in Umbraco 8

I Use a Surfacecontroller to walk through my content, i have added a SeoSiteMap boolean property in Umbraco, so i can disable certain pages, which should not be included in the sitemap. 

I have used this code on multiple sites, with no issues so far.

And i belive it will mostly work on v7 aswell. 

public class XmlSitemapSurfaceController : SurfaceController
    {
		// {domain}/umbraco/surface/xmlsitemapsurface/generatexmlsitemap
		public FileResult GenerateXmlSiteMap()
		{
			var _nodeHelper = new NodeHelper(HttpContext, Umbraco);
			var home = _nodeHelper.GetFrontpage(); // find the home node.
			var children = home.Descendants<ISEO>().Where(x => x.SeoSiteMap == true); // get needed content from each page.
			var sitemapList = new List<SitemapModel>(); //initiate new list.

			// to include the homenode aswell.
			var homeSitemapItem = new SitemapModel()
			{
				Loc = home.Url(mode: UrlMode.Absolute),
				Lastmod = home.UpdateDate,
				Priority = "0.8",
				ChangeFreq = "monthly"
			};
			sitemapList.Add(homeSitemapItem);

			// add all the children of home.
			foreach (var item in children)
			{
				var sitemapItem = new SitemapModel()
				{
					Loc = item.Url(mode: UrlMode.Absolute),
					Lastmod = item.UpdateDate,
					Priority = "0.8",
					ChangeFreq = "monthly"
				};
				sitemapList.Add(sitemapItem);
			}

			// Generate XML in proper format.
			var xml = GenerateXml(sitemapList);
			// return as XML.
			var stream = new MemoryStream();
			var writer = XmlWriter.Create(stream);
			xml.WriteTo(writer);
			writer.Flush();
			stream.Seek(0, SeekOrigin.Begin);
			return File(stream, "text/xml", "sitemap.xml"); // returns an XML file with name sitemap.xml
		}
		public XDocument GenerateXml(IEnumerable<SitemapModel> data)
		{
			XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
			XNamespace xsiNs = "http://www.w3.org/2001/XMLSchema-instance";
			XDocument doc = new XDocument(
				  new XDeclaration("1.0", "UTF-8", "no"),
				  new XElement(ns + "urlset",
				  new XAttribute(XNamespace.Xmlns + "xsi", xsiNs),
				  new XAttribute(xsiNs + "schemeLocation",
						 "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"),
				  GenerateElements(data, ns)

			));
			return doc;
		}
		public IEnumerable<XElement> GenerateElements(IEnumerable<SitemapModel> data, XNamespace ns)
		{
			List<XElement> elements = new List<XElement>();
			foreach (var item in data)
			{
				var element = new XElement(ns + "url",
												   new XElement(ns + "loc", item.Loc),
												   new XElement(ns + "lastmod", item.Lastmod),
												   new XElement(ns + "changefreq", item.ChangeFreq),
												   new XElement(ns + "priority", item.Priority)
											);
				elements.Add(element);
			}
			return elements;
		}
	}

Leave a Reply

Your email address will not be published. Required fields are marked *