.net and other musings

Ben Lovell, an agile developer living in the UK.

Monorail – objects as XML

with 2 comments

While we’re on the subject of objects and XML I’ll show you my preferred approach via Monorail:

The following action is exposed on the Publisher controller:

public void Xml([ARFetch("id")] Publisher publisher)
{
    Context.Response.ContentType = "text/xml";
    PropertyBag["publisher"] = publisher;
    RenderView("xml", true /*skipLayout*/);
}

As you can see, we’re using the ARSmartDispatcherController and ARFetch attribute magic to fetch the correct publisher based on the supplied id querystring parameter. We then set the content type to XML and store the publisher in the property bag so we can get at it in the view. Then, simply render the view displayed below, and skip the layout so we don’t get the HTML stuff specified in our default layout on the controller:

<?xml version="1.0"?>
<publisher>
    <id>$publisher.id</id>
    <name>$publisher.name</name>
    <city>$publisher.city</city>
    <country>$publisher.country</country>
</publisher>

If we hit the following URI: /publisher/xml.rails?id=1 we are presented with the publisher object as XML:

xmloutput

This way, the view is totally responsible for the transformation. Consider the XML representation of an object to be a presentation concern and it makes perfect sense.

Written by benl

June 9, 2007 at 11:10 am

Posted in .NET, Monorail

2 Responses

Subscribe to comments with RSS.

  1. Check out BooML + Brail.
    That can make XML much easier to work with.

    Ayende Rahien

    June 9, 2007 at 8:49 pm

  2. This works great as long as you don’t have many to one relationship properties in your model. For instance if your Publisher has a Regions property that is decorated with a BelongsTo attribute it would fail.

    Maruis Marais

    June 28, 2007 at 10:30 pm


Leave a Reply