Created
March 23, 2016 01:13
-
-
Save martinabrahams/f8b337a760d4320d75a6 to your computer and use it in GitHub Desktop.
Generate Umbraco Sitemap with HREF Lang tags
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static byte[] GenerateSiteMap(IPublishedContent model) | |
{ | |
var sites = model.Parent.Children.Where(x => x.DocumentTypeAlias == "HomePage" || x.DocumentTypeAlias == "SatelliteHomePage"); | |
var baseUrl = string.Format("{0}://{1}", HttpContext.Current.Request.IsSecureConnection ? "https" : "http", HttpContext.Current.Request.Url.Host); | |
var siteMap = new XmlSiteMap(); | |
foreach (var homePage in sites) | |
{ | |
siteMap.Urls.Add(GetPage(baseUrl, homePage)); | |
siteMap.Urls.AddRange(GetChildPages(homePage, baseUrl)); | |
} | |
// create xml feed | |
XNamespace xmlns = "http://www.w3.org/1999/xhtml"; | |
XNamespace sitemapns = "http://www.sitemaps.org/schemas/sitemap/0.9"; | |
var xdoc = new XDocument( | |
new XDeclaration("1.0", "UTF-8", null), | |
new XElement(sitemapns + "urlset", | |
new XAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"), | |
new XAttribute(XNamespace.Xmlns + "xhtml", "http://www.w3.org/1999/xhtml") | |
) | |
); | |
for (int i = 0; i < siteMap.Urls.Count; i++) | |
{ | |
var doc = siteMap.Urls[i]; | |
var item = new XElement(sitemapns + "url"); | |
item.Add(new XElement(sitemapns + "loc", doc.Url)); | |
item.Add(new XElement(sitemapns + "lastmod", doc.Modified)); | |
if (doc.Alternates != null && doc.Alternates.Any()) | |
{ | |
foreach (var alt in doc.Alternates) | |
{ | |
if (alt.Lang != null && alt.Url != null) | |
item.Add(new XElement(xmlns + "link", new XAttribute("rel", "alternate"), new XAttribute("hreflang", alt.Lang), new XAttribute("href", alt.Url))); | |
} | |
} | |
xdoc.Root.Add(item); | |
} | |
using (var ms = new MemoryStream()) | |
{ | |
using (var sw = new StreamWriter(ms, Encoding.UTF8)) | |
{ | |
xdoc.Save(sw); | |
return ms.ToArray(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment