My client required a google product feed representing their store products, so I decided to make use of Linq-to-Xml to generate the Xml markup and Linq-to-Objects to retrieve my product data.
Initially I had my doubts about using Linq, however, since seeing how efficient and clean the code was compared to using XPath, I'm now a believer ;)
Here is the code. Copy and paste this into a Test.aspx page.
Note that you'll need an object collection of your products to quickly re-use this code. This can be a generic List<Product> too.
I've loaded my product collection at the top of the Page_Load event. Replace this with your own and update the elements with your product collection properties.
<%@ Page Language="C#" AutoEventWireup="true"%>
<%@ Import Namespace="System.Xml"%>
<%@ Import Namespace="System.Linq"%>
<%@ Import Namespace="System.Xml.Linq"%>
protected void Page_Load(object sender, EventArgs e)
// load your product collection here
ProductCollection pc = ProductCollection.Load(false);
XNamespace g = "http://base.google.com/ns/1.0";
XDocument doc = new XDocument(
new XDeclaration("1.0", null, null),
//new XComment("Sample RSS Feed"),
new XAttribute("version", "2.0"),
new XAttribute(XNamespace.Xmlns + "g", g), //"http://base.google.com/ns/1.0"
new XElement("title", "eStore Products for XYZ"),
new XElement("link", "http://" + Request.Url.Host),
new XElement("description", "Products available at our store."),
from product in pc
orderby product.Name ascending
select new XElement("item",
new XElement("title", product.Name),
new XElement("link", "http://" + Request.Url.Host + RouteHelper.Parse("/product.aspx?ProductID=" + product.ID)),
new XElement("description", product.Description),
new XElement(g + "image_link", "http://" + Request.Url.Host + product.DefaultImage + CustomImage.Get80x80),
new XElement(g + "price", product.Price)
// save Xml output to website/app root folder
doc.Save(Server.MapPath("~/") + "products.xml", SaveOptions.None);
// debug to html
// Response.Write(new XDeclaration("1.0", null, null).ToString() + "\r\n" + doc.ToString());
Call your Test.aspx page and your Xml will get generated.
In case you're confused about the XNamespace, basically we are using this to create special Google Product Feed Xml element name, but that is a topic for another article. All we need to know is that its necessary to build elements that contain the colon (:) character.