At Sitecore we often talk about the many uses of the Device concept. Sometimes this is obvious (a mobile device requesting content vs. a browser requesting content will expect some particulars around the HTML sent to it). Sometimes it is a bit more subtle (Internet Explorer and Firefox continue to disagree about something, so I have a control that implements a method or CSS class a bit differently based on the detection of the browser). One of the situations we often talk about is the ease of availability of an XML representation of each content item in the content tree. This conversation often centers around integration points, where I can send an XSLT-translated XML document based on Sitecore content to an external application or Web service.
I wanted to prove in a quick concept--creating a Device presentation layer that shows an XML document based on the requested content item. I took the easy way out in many areas of this, and I welcome real world "yeah, but this is actually how you should do it" wherever appropriate. Basically, I started by creating the Device in Sitecore. I called it XML and added it to the Devices in the content tree.
The new XML device is defined by any URL with xml=1 included in the query string. To keep things simple, I created a new Layout (.aspx) file to handle requests from the XML device. The Layout has a statically placed control (RenderXML.ascx) that does the work of:
-
Creating an XML document out of the fields of the Sitecore context item (the currently requested item from the content tree) -
Transfer the request (Server.Transfer) to the newly created XML document (allowing the browser's CSS for XML files to format the display).
The code that does this, in the Page_Load event within RenderXML.ascs.cs, is shown below:
protected voidPage_Load(objectsender, EventArgs e) {
Sitecore.Data.Items.ItemthisItem = Sitecore.Context.Item;
XmlTextWriter writer = newXmlTextWriter(Server.MapPath("/layouts/dynamic/XmlDevice.xml"),System.Text.Encoding.UTF8);
writer.WriteStartDocument();
writer.WriteStartElement("item");
writer.WriteAttributeString("name", thisItem.Name);
foreach(Sitecore.Data.Fields.Fieldfld inthisItem.Fields)
{
writer.WriteStartElement("field");
writer.WriteAttributeString("name", fld.Name);
writer.WriteAttributeString("value", fld.Value);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
Server.Transfer("/layouts/dynamic/XMLDevice.xml");
}

