Wednesday, May 7, 2008

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

Facebook

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> david@david.com< /email> < /application>
< application> < name> Mercantile House< /name> < email> binod@hotmail.com< /email> < /application>
< application> < name> BishowShop< /name> < email> bishow@hotmail.com< /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=[]
java.net.URL url= this.getClass().getClassLoader().getResource("EmailInfo.xml");
java.net.URI uri = new URI(url.toString())
File f=new File(uri)
def emailInfo = new XmlSlurper().parse(f) //Specific to groovy
emailInfo.application.name.each {appName += it} //specific to groovy
emailInfo.application.email.each {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)
emailMap.put(appName[i].toString(),appEmail[i].toString())

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

println emailMap[“Mercantile House”] //prints binod@hotmail.com

5 comments:

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[it.name] = it.email
}

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 !

Pages

 ©mytechtoday.com 2006-2010

 ©Mytechtoday

TOP