Resolving Grails XML references in ActionScript / Flex
Grails uses XPath in its XML converter, which requires additional processing in the Flex / ActionScript world. This post introduces a very simple solution that converts XML references into non-reference nodes.
This is a quick and dirty solution to a question posted by _HATES in the comments. Thanks for reading my blog.
The problem:
When you use Content Negotiation and the result has two references to the same item, Grails will render the second reference in an xml like the following:
<customer id=”1″>
<country reference=”/list/grill/grillvariations/grillVariation/customers/customer/country”/>
</customer>
ActionScript e4x lacks native support for the XPath format ( although there are external libraries like XPath-as3 that will do this for you).
For a recent project, I had to write my own resolver ( due to problems in SWF loading that affect ActionScript libraries ). Since this is something that might come up when you’re using Flex as a client for Grails, I thought I would share the funciton:
To use it, simply call:
var resolvedValue = xml ( fileWithAPotentialReference, GrailsResult );
private function xml(reference : XML, parentXML : XML) : XML {
var resolved : XML = null;
if ( reference!=null && reference.@id !=null && reference.@id.toString() != "") {
resolved = reference;
} else {
var path : String = reference.@reference;
var tokens : Array = path.split( "/" );
var currentLocation : XML = parentXML;
for each( var token : String in tokens ){
var index : int = 0;
if( token!= "" && token!="list"){
if( token.indexOf("[") > 0 ) {
var check : String = token.substr( token.indexOf("[")+1, token.indexOf("]")-1 );
index = parseInt(check )-1;
token = token.substr( 0, token.indexOf( "[" ));
}
var nextLocation:XML = currentLocation.elements(token)[index];
if( nextLocation!= null ){
currentLocation = nextLocation;
}
}
}
resolved = currentLocation; }
return resolved; }
Brilliant! Thanks a lot for sharing.
Hates_
August 3, 2008 at 12:20 pm