Tuesday, June 29, 2010

Parsing XML: two stumbling blocks and a problem with params

Today I wanted to parse some XML content from NCBI into my grails application. I followed the instructions on:

http://www.ibm.com/developerworks/java/library/j-grails05208/index.html

Although the connection did not seem to have any problems, the parsing from a XMLSlurper object to a map did. There were in fact two problems I had to face and luckily I found the solution for both of them here:

http://stackoverflow.com/questions/1849547/groovy-xmlslurper-not-parse-my-xml-file

The first problem was that you cannot have a dash in your XML node unless you embrace it with hyphens like this:
ncbiXML.GBSeq.'GBSeq_accession-version' as String

I guess dashes are otherwise interpreted like dots (separators). I imagined something like that when I encountered the error "no property like that".

After fixing this the code ran through. The tests however still failed as only empty values were returned. The solution was to ignore the top node of the XML input. Starting one node below everything worked fine.

Now, equiped with a nice map I wanted to create domain objects following the helpful steps at the end of this article:

http://thediscoblog.com/2009/02/19/restful-grails-services-in-3-steps/

To make the properties editable before submission, I added a new action to a controller that redirects to "create" and hands over the xml parsed map from XMLSlurper as params.

That would probably have worked if it hadn't been for one property that was not a string, but an object. I thought no problem, all I have to do is use a dynamic finder to get my object with the string. This produces errors as grails interpreted this parameter as String and threw conversion exceptions when trying to parse a string to my object:

Cannot convert value of type [java.lang.String] to required type

I have googled for hours and tried everything, but finally I found the very simple solution. You have to put it like this to convince grails that it has to look up for a domain object itself via id:

ncbiMap.'organism.id' = organism.id

Again, the hyphens are very important. In the beginning I tried different things without them and then grails tries to resolve the dot instead of letting the parameter go.

Now everything works fine and I hope someone can use this to get started real fast on this (not like me :-)

No comments:

Post a Comment