XMLBeans is a fantastic technology provided by Apache which is used for marshalling and un-marshalling XML.This helps us to bind XML into Java Types.In this blog, I will first introduce the scenario where XMLBeans comes handy.While progressing I will mention about the configuration required , generating the Java classes and using them.
Lets take the scenario where the user requests the server for some response and assume the response comes in the form of xml file.The xml file will be formatted and will have exactly one root element.The root element may have different child nodes.Suppose the xml file consists of list of flights ,along with their departure and arrival timings and the fares.We want the details related to the flight to be displayed in the list .The XMLBeans technology will generate the Java classes along with the corresponding getters and setters method.If necessary, it also creates the array for particular elements.
For starting with XMLBeans , we should have the sdk installed.You can download the sdk at http://www.apache.org/dyn/closer.cgi/xmlbeans.Once downloaded extract the folder at some location and set the environment variables for XMLBeans as mentioned below.
export XMLBEANS_HOME=<location of XMLBeans root> (e.g /home/tanweer/xmlbeans-2.5.0)
export PATH=$PATH:$XMLBEANS_HOME/bin
export CLASSPATH=$XMLBEANS_HOME/lib/xbean.jar:$XMLBEANS_HOME/lib/jsr173_1.0_api.jar:$CLASSPATH
Enter the command scomp in the terminal to check whether the path is set correctly or not.
The input to the xml beans scomp (schema compiler) is the .xsd file .
The .xsd file is considered as the grammar of xml.In terms of Java we can say .xsd file is the Java class which defines the object model and .xml file is the Java Object with real content.
To generate the equivalent Java classes for .xsd file ,in the terminal go to the location of the xsd file.Enter the scomp command like :
$location_of_xsd : scomp -out test.jar test.xsd
where test.xsd is the schema file and test.jar is the jar file with all the classes generated.These generated classes have the getters and the setters for accessing the elements of the xml.We can also generate the .java files with proper scomp command.
Copy this jar file ,put it inside the lib folder.Add the jar file to the build path.Import the package and the classes.
Once imported you can go through the classes and the methods.
There are also other technologies like JAXB but XMLBeans are light-weight and even the performance is better.