Sitecore Item Web API XML Maintaining Sitecore SPEAK

Recently I have had a client request asking to use Sitecore Item Web API in XML format rather than JSON. Luckily within the Item Web API documentation Sitecore provide a Pipeline Processor to output XML rather than JSON.  http://sdn.sitecore.net/upload/sdn5/modules/sitecore%20item%20web%20api/sitecore_item_web_api_developer_guide_sc66-71-a4.pdf

Sitecore SPEAK also makes use of the Sitecore Item Web API, but an unfortunate side effect of this code snippet is that it breaks Sitecore SPEAK as it expects JSON responses back from the web service. The code snippet below is an adapted version of the Sitecore code snippet. It allows bypassing the XMLSerializer by default unless a query string parameter of “type=xml” is present.

This allows you to maintain Sitecore SPEAK functionality while allowing the calling client to easily switch between JSON and XML. Add this XML to the include folder in app_config

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
 <sitecore>
 <pipelines>
 <itemWebApiRequest>
 <processor patch:before="*[@type='Sitecore.ItemWebApi.Pipelines.Request.SerializeResponse, Sitecore.ItemWebApi']" type="MikeRobbins.CMS.WebItemAPI.SwitchToXmlSerializer,MikeRobbins.CMS" />
 </itemWebApiRequest>
 </pipelines>
 </sitecore>
</configuration>
namespace MikeRobbins.CMS.WebItemAPI
{
 public class SwitchToXmlSerializer : RequestProcessor
 {
 public override void Process([NotNull] RequestArgs arguments)
 {
 if (System.Web.HttpContext.Current.Request.QueryString["type"] == "xml")
 {
 Context.Current.Serializer = new XmlSerializer();
 }
 }
 }
}
namespace MikeRobbins.CMS.WebItemAPI
{
 public class XmlSerializer : ISerializer
 {
 public string SerializedDataMediaType
 {
 get
 {
 return "text/xml";
 }
 }

 public string Serialize(object value)
 {
 return Serialize((Dynamic)value).ToString();
 }

 private XElement Serialize(Dynamic value)
 {
 var element = XElement.Parse("<object/>");

 foreach (var property in value)
 {
 var propertyName = string.Format("_{0}", property.Key);
 propertyName = propertyName.Replace("{", "");
 propertyName = propertyName.Replace("}", "");
 propertyName = propertyName.Replace(" ", "-");

 var child = XElement.Parse(string.Format("<{0}/>", propertyName));
 var array = property.Value as Dynamic[];

 if (array != null)
 {
 foreach (var item in array)
 {
 child.Add(Serialize(item));
 }
 }
 else if (property.Value is Dynamic)
 {
 child.Add(Serialize((Dynamic)property.Value));
 }
 else
 {
 child.Add(property.Value.ToString());
 }

 element.Add(child);
 }

 return element;
 }
 }
}