Pages - Menu

Return XML Datafeed in a MVC Action Result


We are trying to export our products in an xml feed. This will be provided to 3rd party vendor so they can provide search or product reviews for our products, or simply froogle.

I am building a MVC action that will return the XML result in the page when a url is called (so it should display the xml as content in the browser, and view source of the page should show the actual xml file).


During this exercise, I encountered the following errors:-
  • Error message about prefix '' cannot be redefined from '' tag
  • Missing XML Declaration
  • Getting a declaration of UTF-16 instead of UTF-8
  • '', hexadecimal value 0x03, is an invalid character
It is a multiple failure and apparently they are all common and valid errors.


This "little" piece of code fixed quite a few things.

Name Space Prefix

Initially, I tried to put namespace in the XDocument as a XAttribute, that was causing error and the correct way is to add XDeclaration to the Element name.


I intentionally put the declaration in string with the xml.ToString(), there were other solutions like using MemoryStream and Save() to "conserve" the declaration, I just found that is overkilling for such a simple thing.

This also resolve the issue where conversations of MemoryStream that caused UTF-8 became UTF-16.

Invalid Character 

This is because the object (string) that I pass in to the XElement has invalid character. There easiest way and most effective way is to Sanitize the input. I wrote an extension method for this.


Another issue that might arise is the value for XElement might have HTML tags in it. Again, this can be done by another extension method to wrap the value in a CDATA object, the reason for the extension method is this will cater for null value and it looks neater.