XML unmarshalling with Castor and Grails
I have a grails pr开发者_运维百科oject that contains a few domain objects. I am using a java project in this code which can parse a document for me. The controller that calls that Java project is using JAXB to generate XML from the object returned by the Java project. I want to use this XML document (which is generated after some text parsing, using JAXB) to populate my Domain classes in my grails project. How does this work in grails? Can I use something like Castor, and create a mapping using the names of my groovy classes? The idea is I want to generate new entries in the database and save it for the user based on whatever text was parsed out of the document they uploaded.
How does this even work in grails anyway? Can I create a new Domain object from another object's controller with something like
Project p = new Project();
and then do a p.save()
?
Download the Castor Core and Castor XML jars from here and put them in the lib
directory (there's probably a better way to manage this dependency using Grails' dependency management, but this one's a quick and dirty).
With Castor introspection mode you don't need to worry about creating mapping files if your XML matches up nicely with your domains. Here's an example:
grails-app/domain/MyDomain.groovy
class MyDomain {
String foo
String bar
}
grails-app/controllers/MyController.groovy
import org.exolab.castor.xml.Unmarshaller
import java.io.ByteArrayInputStream
class MyController {
def myAction = {
def xml = '''
<myDomain>
<foo>My Foo String</foo>
<bar>My Bar String</bar>
</myDomain>
'''
def reader = new ByteArrayInputStream(xml.bytes).newReader()
def domain = (MyDomain)Unmarshaller.unmarshal(MyDomain.class, reader)
domain.save()
def count = MyDomain.countByFoo('My Foo String')
render "Found $count results"
}
}
Navigate to localhost:8080/appname/my/myAction
and it should display "Found N results", N > 0.
精彩评论