Sitemap XML web service for Kentico / Xperience 13 CMS

Kentico 13 upgrade left us without a sitemap, so we put this one together to replace it. The CMS can provide the sitemap for the presentation front end for Google Console. Useful when your front end can't adjust the header content before it renders itself, like REACT. The below is a web service you can put on a custom API of Kentico/Xperience 13.
 [HttpGet]
        public HttpResponseMessage GetSiteMap()
        {
            string PAGESXML = "";


            List<TreeNode> BusinessListingTreeNodes = DocumentHelper.GetDocuments().Types("React.Page","React.OtherPage").OnCurrentSite()
                .Path("/",PathTypeEnum.Children).Culture("en-GB").CombineWithDefaultCulture(true).Published().PublishedVersion().CheckPermissions(false).NestingLevel(5).ToList();

            var siteurl = CMS.SiteProvider.SiteContext.CurrentSite.SitePresentationURL;

            //remove trailing backslash
            if (siteurl.EndsWith("/"))
            {
                siteurl = siteurl.Substring(0, siteurl.Length - 1);
            }

            if (BusinessListingTreeNodes != null || BusinessListingTreeNodes.Count() > 0)
            {

                foreach (TreeNode ThisPage in BusinessListingTreeNodes)
                {
                    string lastdate = ThisPage.DocumentLastPublished.ToString("yyyy-MM-dd");
                    if (lastdate == "0001-01-01")
                    {
                        PAGESXML += @"<url><loc>" + siteurl + ThisPage.NodeAliasPath.ToLower() + @"</loc>                                
                                </url>";
                    }
                    else
                    {
                        PAGESXML += @"<url><loc>" + siteurl + ThisPage.NodeAliasPath.ToLower() + @"</loc>
                                <lastmod>" + lastdate + @"</lastmod>
                                </url>";
                    }

                }

            }


            string XML = @" 
                            <urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9' xmlns:xhtml='http://www.w3.org/1999/xhtml'>
                                " + PAGESXML + @"
                               
                            </urlset>
            ";
            return new HttpResponseMessage()
            {
                Content = new StringContent(XML, System.Text.Encoding.UTF8, "application/xml")
            };
        }

powered by mition