Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Xml to DB handler - grails tutorial
1. Dalton Valadares – Universidade Federal de Campina Grande
How to populate a DB reading values from a XML file, with GRAILS?
-Suppose your XML is the following:
<Result totalLooseOffers="0" xsi:schemaLocation="http://somewhere.onthe.net/something.xsd">
<details>
<applicationID>37394759ds2k9a2k467626f3d</applicationID>
<date>2013-04-11T14:31:11.490-03:00</date>
<elapsedTime>1</elapsedTime>
<status>success</status>
<code>0</code>
<message>success</message>
</details>
<category concatenateCategoryName="false" hasOffer="false" isFinal="true" parentCategoryId="116" id="3661">
<thumbnail url="http://somewhere.onthe.net/something.jpg"/>
<links>
<link type="category" url="http://somewhere.onthe.net/something/51922611"/>
<link type="xml" url="http://somewhere.onthe.net/something/3739416878456f4/br/>
</links>
<name>Air conditioning </name>
<filters>
<filter name="Brand" id="1246">
<value value="Springer Carrier" id="47204"/>
<value value="LG" id="7018"/>
<value value="Consul" id="7017"/>
<value value="Midea" id="106986"/>
</filter>
<filter name="Type" id="1246">
<value value="Split" id="404"/>
<value value="Window" id="18"/>
<value value="Portable" id="707"/>
<value value="Multi-split" id="1066"/>
</filter>
.
.
.
</category>
-You want to save filters and values into DB;
-With your domain and controller classes created, you will have the save() method implemented;
-Create the class XML_Handler:
import java.awt.GraphicsConfiguration.DefaultBufferCapabilities;
import entities.Filter; //Your domain class for Filters
import entities.Value; //Your domain class for Values
import groovy.util.XmlParser
class XML_Handler {
public static run() {
def air_conditioning = new File("/path_to_file/air_conditioning.xml")
this.insertIntoDB(air_conditioning)
}
static insertIntoDB(File file) {
def my_handler = new XmlParser().parse(file)
2. my_handler.category.filters.filter.each {
Filter filter = new Filter();
filter.description = it.@name
filter.save(flush: true)
println "Filter: " + it.@name + " -----OK!"
it.value.each {
//the attribute filter receives the filter inserted before (created above)...
Value value = new Value(description: it.@value, filter: filter);
value.save(flush: true)
println " Value - " + it.@value + " -----OK!"
}
}
}
-Now, you just need to put the line below to be executed in any part of any controller (you can put a
button to do this function):
XML_Handler.run(); //when the code is executed, the values are inserted into DB
I hope it can help...