开发者

XML unmarshalling with Castor and Grails

开发者 https://www.devze.com 2023-01-16 17:28 出处:网络
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 usin

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号