Monday, 30 March 2015

How to store xml file in database using groovy script

Step1:



Here I'm using mysql dababase
Creating one database schema like "xmldb", in this xmldb schema create a one  table like 'persons'

For this table having field names like: id,firstname,lastname,email,address

Step 2: Write one xml file like 'MyxmlP.xml

MyxmlP.xml
<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person age="3">
        <id>36 </id>
        <firstname>Rama</firstname>
        <lastname>Krishna </lastname>
        <email>rama@krishna.com</email>
        <address>CA</address>
    </person>
    <person age="4">
        <id> 63</id>
        <firstname>krishna</firstname>
        <lastname>rama</lastname>
        <email>krishna@rama</email>
        <address>AC</address>
    </person>
</persons>


Step 3:
Write one scripting file for the database connection and storing xml file into database:

Step 4:
The filename like:
Xml2DB.groovy


/*
 *Stores xml data into mysql database 
 *
 */
class Xml2DB{
    static void main(args){


        def sql = Sql.newInstance("jdbc:mysql://localhost:3306/xmldb", "root",
                "root", "com.mysql.jdbc.Driver")
      
          def Employee  = new XmlParser().parse('MyxmlP.xml')
        //set the database table name here.
        def set1 = sql.dataSet("persons")

        Employee.person.each {
            def empId = it.id.text()
            def firstName = it.firstname.text()
            def lastName = it.lastname.text()
            def email  = it.email.text()
            def empAddress = it.address.text()
           
                  

            set1.add(id:empId,firstname:firstName,lastname:lastName,email:email,address:empAddress)
        }
    }
}





No comments:

Post a Comment