Linq to Xml: Generate Google Sitemap with sitemap-protocol

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

[code language=’c#’]
//create datasource

List blogPosts = new List{

//Create namespace for sitemap-protocol

XNamespace xmlNS = “”;
XDocument xmlDoc =
 new XDocument(
  new XDeclaration(“1.0”, “UTF-8”, null),
  new XElement(xmlNS + “urlset”,
   from blogPostUrl in blogPosts
    new XElement(xmlNS + “url”,
    new XElement(xmlNS + “loc”, blogPostUrl))

//Show output



This example will give the following output:

[code language=’xml’]
<urlset xmlns="“>


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.

Convert XmlElement to XElement (Extension Method)

I was using some web-services that returned there values in an XmlElement. I needed to convert this XmlElement to something that I can use with LINQ. I didn't find good solutions on the internet. So I started building my own convert logic. After all kinds of solutions I ended up with creating an new XmlDocument, adding the XmlElement to the XmlDocument and then convert the innerXml of the XmlDocument to an XElement. Not really nice but it does the trick.

I've rewritten the code into a Extension Method for the XmlElement.


public static XElement ToXElement(this XmlElement xml)
   XmlDocument doc = new XmlDocument();

   doc.AppendChild(doc.ImportNode(xml, true));

   return XElement.Parse(doc.InnerXml);



You use the Extension Method like this:


XmlElement xmlElement = wsClient.DoWebServiceRequest();
XElement xml = xmlElement.ToXElement();


Please tell me if you have a better way of doing this!