Chitika

Friday, August 3, 2012

Add/Update sitemap dynamically using XML & LINQ in ASP.net



         Recently in one of my projects we had a situation to add/update the content in the sitemap, i found the best solution to do it using LINQ. In this you will learn how to create an ASP.NET Sitemap file dynamically.

1)Right click on your project -->Add New Item-->site map(Web.sitemap)
                                        keep  the same name


Click on Add button , then you can see the default sitemap file as below



2)Go to source view of your .aspx page add button and in the click event of that button write the following code

source view:
  <h2>
        Add/Update Site map
    </h2>
    <p>
        <asp:Button Text="Add/Update Site Map" runat="server" OnClick="Unnamed1_Click" />
    </p>


 Now we need to make content to add/ update the sitemap.
on click of the button write the following code first add  top


using System.Xml.Linq ;     because we are using  


XNamespace --> for XML name space
XDocument  --> for XML document
XDeclaration --> for XML version & encoding type
XElement     --> for XML elements



    protected void btnSitMap_Click(object sender, EventArgs e)
    {
        try
        {
// you can get the details from the db then add it to XElement list as below,

            List<XElement> products = new List<XElement>();

 // i want to add 9 nodes to site map
            for (int product = 1; product < 10; product++)
            {
                products.Add(new XElement("siteMapNode",
                   new XAttribute("title", "LG Dvd Writer_"+product.ToString()),
//give the product details path , here my routing path
                  new XAttribute("url", "~/Products/LG Dvd Writer_"+product.ToString())));
            }
            XNamespace siteNM = "http://schemas.microsoft.com/AspNet/SiteMap-File-1.0";

//Adding product elements list to XML document

//and Saving XML document data in Web.sitemap file


            new XDocument(
                        new XDeclaration("1.0", "UTF-8", null),
                         new XElement(siteNM + "siteMap", products)).Save(Server.MapPath("Web.sitemap"));
        }
        catch (Exception)
        {
        }



That's end now run the project & click on the button as you observe the sitemap file is updated.



 As you observer the compilation error for "siteMapNode", because of xmlns is empty to avoid it just add the namespace for every element.


Hope, you got how to add/update the sitemap in asp.net.

For  more information about sitemap visit