Dynamically Generate Meta Tags for ASP.NET Pages using LINQ To XML

Posted by: Malcolm Sheridan , on 5/19/2009, in Category ASP.NET
Views: 61663
Abstract: The following article demonstrates how to use LINQ to XML to dynamically generate meta tags for different ASP.NET pages.
Dynamically Generate Meta Tags for ASP.NET Pages using LINQ To XML
We all know how important it is to use meta tags when you’re building an internet web site. Meta tags provide metadata about the HTML document. They are not rendered in the browser but are used by search engines to parse web pages. The following article demonstrates how to store meta tags for each page in an XML file and how to use LINQ to read the XML data and dynamically create meta tags for each page in your website.
Open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application.
Add a Master Page to the project. Once that is completed, add a Web Content Page and select the newly created Master Page as the Master Page.
The next step is to create a new folder in the web site to demonstrate all pages in the website will have dynamic meta tags at runtime. Right click the website and choose Add > New Folder. Name the new folder ChildFolder. After this add a new Web Content Page to this folder. Leave the default name as this is not important. 
Now that we have two pages in different folders, it’s now time to create an XML file that contains the data for the meta tags. Right click the website and choose Add > New Item > XML File. Name the file TagData.xml and add the following XML:
 <tags pageName="/WebForm1.aspx">
    <tag name="keyword" value="This is a keyword"></tag>
    <tag name="description" value="This is a description"></tag>
    <tag name="author" value="malcolm sheridan"></tag>
 <tags pageName="/ChildFolder/WebForm1.aspx">
    <tag name="keyword" value="This is a keyword for the child pages"></tag>
    <tag name="description" value="This is a description for the child pages"></tag>
    <tag name="author" value="malcolm sheridan for this page too"></tag>
In the XML above I have created a parent node called metaTags. Inside I have created a tags node which contains a pageName attribute. That value is how we will match the current requested page to the XML data. Each tags node contains a tag node that corresponds to the meta data we want sent to the browser. In this example I want to set meta tags for the all the pages to have keyword, description and author meta tags, but the values rendered to the browser will differ depending on what page the user is on. In a real world scenario this information would be stored inside a database, but I decided to keep this data inside an XML file to keep it simple and focus on how to do this.
Having outlined what meta tags we want sent to the browser, we now have to write the code that will read the XML file and dynamically add the meta tags at runtime. Seeing as though we’re using Master Pages this is the ideal spot to add it. Add the following code to read the XML file:
XDocument doc = XDocument.Load(Server.MapPath("~/TagData.xml"));
var metaTags = doc.Descendants("tag")
              .Where(o => o.Parent.Attribute("pageName").Value == Request.Url.AbsolutePath)
               .Select(o => new
                    Value = o.Attribute("value").Value,
                    Name = o.Attribute("name").Value
Dim doc As XDocument = XDocument.Load(Server.MapPath("~/TagData.xml"))
Dim metaTags = doc.Descendants("tag").Where(Function(o) o.Parent.Attribute("pageName").Value = Request.Url.AbsolutePath).Select(Function(o) New With {Key .Value = o.Attribute("value").Value, Key .Name = o.Attribute("name").Value})
For flexibility and ease of use I have decided to use the power of LINQ to XML to read the XML data. To start with the XML document is load into an XDocument object. From there I have created a LINQ query to return all the tag nodes where the parent node has an attribute called pageName and the value is equal to the current page.   Then the object returned is an anonymous type that has a Value and Name property. The values of those properties are the value and name attribute values. 
Now that we have the data in memory, the next step is to create the meta tag and add it to the page dynamically. To do this you use the HtmlMeta class. This allows you programmatic access to the HTML meta tags. Add the following code below to your project:
foreach (var item in metaTags)
     HtmlMeta meta = new HtmlMeta();
     meta.Name = item.Name;
     meta.Content = item.Value;
For Each item In metaTags
       Dim meta As New HtmlMeta()
       meta.Name = item.Name
       meta.Content = item.Value
Next item
The foreach loop enumerates through each item returned from the LINQ query. It assigns the Name and Content value to the HtmlMeta object. Finally the object is added to the page by calling Page.Header.Controls.Add(meta). Run the project and once the default page has loaded, view the HTML source and you’ll see the meta tags have been added to the website.
Browsing to the second page and viewing the HTML source, you’ll find the meta tags have been added to the page but they’re different values from the previous page.
I hope you have found this article of interest. Meta tags are a great way to describe your website to the outside world, and this way you can dynamically add this data with LINQ. Is there anything LINQ can’t do? The entire source code of this article can be downloaded from here.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Ken B on Monday, May 25, 2009 7:05 AM
we have been struggling to do this, got saved. Thanks.
Comment posted by saburius on Friday, June 5, 2009 6:00 PM
Very helpful article. Thank you. The questions I would have are, how can the user edit/update the meta tags? Would each dynamic page have a separate xml file for meta? Would be great to have a server control that could work with xml file like the other data controls with database - and save roundtrips to database.
Comment posted by Malcolm Sheridan on Wednesday, June 10, 2009 2:26 AM
The meta tags would be updated by the developer, not the user.  If you needed the user to be able to update the meta tags then you would have to update the xml file.  The cost of reading an xml file is minimal, but you could add the xml file to the cache and let it decide when it changes.
Comment posted by abhijitkharde on Friday, July 17, 2009 10:25 AM
Hi Malcolm Sheridan, this is a pretty nice site where I found plenty of useful articles on MS.NET technologies. Could you please suggest how can I download all of these articles in on go ? Thanks for such a nice site.
Comment posted by Bambrick on Saturday, July 18, 2009 11:22 AM
indeed this is one of the top sites but I do not think any website would give you that option to d/load all articles at one go. I have subscribed to the rss using email and I get the articles delivered to my mailbox.
Comment posted by Malcolm Sheridan on Friday, July 24, 2009 12:43 AM
Do what Banbrick does and subscribe to the RSS feed.  There's no way to download all the articles in one go.
Comment posted by Jack on Friday, July 24, 2009 5:04 PM
A complicated solution for a simple problem. Two fields in a database would simplify this problem for a typical cms system.   Most developers I know would never put content data inside of an xml file.  Meta tags are content related fields and should be updated by the user/admin via a form.
Comment posted by Rajib on Sunday, July 26, 2009 3:28 PM
This is good, but if you have a large set of pages there would be dependencies to the file.  Any time something changes, there may be a locking issue.  One must make sure to put a cache dependency on the xml file.  I agree with Jack.  Keep it in the database, and cache your controls and pages, and you'll be set!
Comment posted by Bob McIntyre on Wednesday, August 26, 2009 9:42 PM
How is this done in Expression Web? I'm having tons of trouble figuring that out...and it's important!
Comment posted by affordable seo on Thursday, September 17, 2009 5:08 PM
I haven't any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.i found this informative and interesting blog so i think so its very useful and knowledge able.I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. <a href="http://charismaticseo.blogspot.com">seo techniques</a>In fact your creative writing abilities has inspired me.Really the blogging is spreading its wings rapidly. Your write up is fine example of it
Comment posted by Malcolm Sheridan on Monday, September 21, 2009 11:19 PM
@affordable seo
Thanks for the kind words.  I'm glad you liked it.

@Jack, @Rajib
Yes if you have a large set of pages, moving this data to the database might be more suitable.  And yes it's a good idea using the cache dependency on the file.  
Comment posted by Ranjan on Sunday, October 24, 2010 1:53 AM
I like this tutorial. Its very help full for me. I used this in my site www.traceindia.info. Please explore it for trace mobile number.
Comment posted by Ddee on Tuesday, March 20, 2012 1:55 PM
Hi Malcolm,  This is a great tutorial and it worked perfectly on a first try.  Thanks so much.
I am wondering can I use this for the website create in sharepoint 2007???  

Comment posted by Kaushalendra Pandey on Monday, October 29, 2012 7:43 AM
What I want to ask whether the crawler reads these kind of dynamic title, meta tags etc. in other words is it helpful in SEO also or not.