Pieter Brinkman

Linq to Xml: Generate Google Sitemap with sitemap-protocol

1 min readpieterASP.NetGooglelinqXML

In this example I will generate a XML site-map that complies with the sitemap-protocol XML schema.

//create datasource List blogPosts = new List{  "http://blog.newguid.net/mypost1.aspx",  "http://blog.newguid.net/mypost\_about\_Net.aspx",  "http://blog.newguid.net/morePosts.aspx",  "http://blog.newguid.net/andEvenMorePosts.aspx" };
//Create namespace for sitemap-protocol XNamespace xmlNS = "http://www.sitemaps.org/schemas/sitemap/0.9";
XDocument xmlDoc =  new XDocument(   new XDeclaration("1.0", "UTF-8", null),   new XElement(xmlNS + "urlset",    from blogPostUrl in blogPosts    select     new XElement(xmlNS + "url",     new XElement(xmlNS + "loc", blogPostUrl))     ));
//Show output Response.Write(xmlDoc);

This example will give the following output:

<urlset xmlns="[http://www.sitemaps.org/schemas/sitemap/0.9](http://www.sitemaps.org/schemas/sitemap/0.9)">       http://blog.newguid.net/mypost1.aspx         http://blog.newguid.net/mypost\_about\_Net.aspx         http://blog.newguid.net/morePosts.aspx         http://blog.newguid.net/andEvenMorePosts.aspx

To keep the example as simple as possible I only use the LOC element of the URL node. In the real world you can implement the lastmod, changefreq and priority node. More information about the sitemap-protocol.