Wednesday, May 7, 2008

Read custom created XML file from a Groovy/Java class in a J2EE Web Application


I have a following xml file that I created to store the application name and Application Owner email address

//File name: EmailInfo.xml

< emailInfo>
< application> < name> Saleways < /name> < email>< /email> < /application>
< application> < name> Mercantile House< /name> < email>< /email> < /application>
< application> < name> BishowShop< /name> < email>< /email> < /application>
< /emailInfo>

Now I have a J2EE application that contains a Groovy or a Java class that access the above XML file. The method to access above html file using Groovy is presented below. Note that the xml file resides on the same location where the class exists.

def appName=[]
def appEmail=[] url= this.getClass().getClassLoader().getResource("EmailInfo.xml"); uri = new URI(url.toString())
File f=new File(uri)
def emailInfo = new XmlSlurper().parse(f) //Specific to groovy {appName += it} //specific to groovy {appEmail += it} // specific to groovy

You simply can modify the above code for java classes. The final result for the above code is that appName contains the list of the Name and appEmail contains the list of the Email address. You can put it into hash map as below.

def emailMap=[:] //define an empty map
for(i in 0 .. appName.size()-1)

Now you simply can access the email address of a person as shown below

println emailMap[“Mercantile House”] //prints


Anonymous said...

Thanks for your posting.

Anonymous said...

Does XmlSlurper use DOM or SAX or Stax model of parsing?

Bishow Paudel said...

As far as my knowledge DOM or SAX or Stax model of parsing are supported by Java. But XMLSluper is basically Groovy based parser that use SAX underneath.

Anonymous said...

Good post - just a point on the final step. If you are creating two arrays like that appName&appEmail you don't know they are in synch (eg one application owner might not have an email)

You can use the same approach though to create the map:

emailInfo.application.each {
emailMap[] =

custom research paper said...

Many institutions limit access to their online information. Making this information available will be an asset to all.

Post a Comment

I love to entertain onymous user Comment !


 © 2006-2010