Monorail – objects as XML
by benl
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:
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.
Check out BooML + Brail.
That can make XML much easier to work with.
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.