Search code examples
razorsitemapwebmatrixauto-generate

Generate sitemap on a website made ​​with WebMatrix + Razor


I need to generate a sitemap to validate the site with Google Webmaster Tool.

How can I generate the sitemap for my website automatically?


Solution

  • Try this sample:

    @using System.Xml.Linq;
    @{
        var urls = new List<string>{"home", "about", "contact"};
        XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
        var baseurl = "http://www.domain.com/{0}";
        var sitemap = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),
                new XElement(ns + "urlset",
                    from url in urls select
                    new XElement("url",
                        new XElement("loc", string.Format(baseurl, url)),
                        new XElement("lastmod", String.Format("{0:yyyy-MM-dd}", DateTime.Now)),
                        new XElement("changefreq", "monthly"),
                        new XElement("priority", "0.5")
                        )
                    )
                );
        Response.ContentType = "text/xml";
        sitemap.Save(Response.Output);
    }
    

    Save the file as Sitemap.cshtml. Obviously, you will need to replace the List with a source of locations for the map. But at least you can see how the XML is generated.