Apache XML Beans Description:
Apache XML Beans is a set of tools and class libraries used to generate a
JAR library specifically for an XML schema as defined by an XSD file.
The generated library can be used for XML parsing or XML generation conforming to a specified XSD schema.
JAXB and XML Beans are the two prominent XML parsing and generation frameworks.
- XML Beans: supports the entire XSD/XML standard. Although it loads the entire document, XML Beans can also parse only the elements and attributes you are looking for.
- JAXB: loads XML file data into a Java class generated by JAXB as defined by the XSD schema. If the final destination of the data is a class of another definition, the data will have to pass through this intermediate JAXB class.
Both XML Beans and JAXB are reasonably fast.
The most significant difference for the developer is in the handling of "mixed types".
XML Beans handles this effortlessly with no code changes required for "true" or "false" while JAXB requires different code for each case.
See
discussion on the mixed content complex type at the end of this tutorial.
This tutorial will cover the use of XML Beans for parsing an XML file.
XML Beans Installation:
Download latest binaries from http://xmlbeans.apache.org/
Install:
cd /opt
tar xzf ~/Downloads/xmlbeans-2.5.0.tgz
Add to PATH and CLASSPATH:
-
File: ~/.bashrc
4 | if [ -d /opt/xmlbeans-2.5.0 ] |
6 | PATH=$PATH:/opt/xmlbeans-2.5.0/bin |
7 | export CLASSPATH=$CLASSPATH:/opt/xmlbeans-2.5.0/lib/xbean.jar |
XML Beans and Java programming require the installation of Java.
See our YoLinux Java Tutorial.
Generate a JAR library using XML Beans:
Define an XML schema file (XSD) using your favorite XSD/XML editor:
-
Generate a Java JAR library file from the XSD: scomp -out corporation.jar corporation.xsd
This will generate the file corporation.jar
Most Java IDE's support the interrogation and use of classes and methods within the JAR file for use by the programmer. You can also employ the following script to view the classes and class methods available:
File: listmeth
2 | echo "List classes and methods available in the JAR file: $1" |
4 | for class in $(jar -tf $1 | grep '.class' ); do |
8 | javap -classpath $1 ${class//.class/}; |
Use: listmeth corporation.jar
List classes and methods available in the JAR file: corporation.jar
public final class noNamespace.ETaxStatus$Factory {
public static noNamespace.ETaxStatus newValue(java.lang.Object);
public static noNamespace.ETaxStatus newInstance();
public static noNamespace.ETaxStatus newInstance(org.apache.xmlbeans.XmlOptions);
public static noNamespace.ETaxStatus parse(java.lang.String) throws org.apache.xmlbeans.XmlException;
public static noNamespace.ETaxStatus parse(java.lang.String, org.apache.xmlbeans.XmlOptions) ...
...
...
Apache XML Beans Example:
File: TestXmlBeans.java
02 | import java.util.ArrayList; |
04 | import noNamespace.RootDocument; |
05 | import noNamespace.RootDocument.Root; |
06 | import noNamespace.RootDocument.Root.People.Employee; |
07 | import noNamespace.RootDocument.Root.People.Employee.Data; |
09 | import org.apache.xmlbeans.XmlException; |
10 | import org.apache.xmlbeans.XmlObject; |
11 | import org.apache.xmlbeans.XmlOptions; |
13 | public class TestXmlBeans |
15 | static public void main (String[] args) throws XmlException |
17 | String fileName = "CorporationMegaX.xml" ; |
25 | System.out.println( "Error! Exception caught" ); |
30 | public static void readFile(String fileName) throws XmlException |
34 | java.io.File inputXMLFile = new java.io.File(fileName); |
35 | RootDocument rootDocument = RootDocument.Factory.parse(inputXMLFile); |
37 | Root root = rootDocument.getRoot(); |
38 | System.out.println( "Corporation: " + root.getCorporation().getName()); |
40 | Employee[] employee = root.getPeople().getEmployeeArray(); |
42 | System.out.println( "There are " + employee.length + " employees." ); |
44 | for ( int pp = 0 ; pp < employee.length; pp++) |
46 | System.out.println( "Employee name: " + employee[pp].getName()); |
47 | System.out.println( " Gender: " + employee[pp].getGender().toString()); |
48 | System.out.println( " Location: " + employee[pp].getDesc().toString()); |
49 | System.out.println( " Cell phone: " + employee[pp].getData().getCellPhone()); |
51 | String employeeTaxStatus = employee[pp].getTaxStatus().toString(); |
52 | if (employeeTaxStatus.equalsIgnoreCase( "US-W2" )) |
54 | System.out.println( " Tax status: W2" ); |
55 | System.out.println( " Employee number: " + employee[pp].getUSW2().getEmpNumber()); |
56 | System.out.println( " Employee manager: " + employee[pp].getUSW2().getManager()); |
57 | System.out.println( " Employee start year: " + employee[pp].getUSW2().getYearStart()); |
59 | else if (employeeTaxStatus.equalsIgnoreCase( "US-1099" )) |
61 | System.out.println( " Tax status: 1099" ); |
62 | System.out.println( " SSN number: " + employee[pp].getUS1099().getSsnNumber()); |
63 | System.out.println( " Phone number: " + employee[pp].getUS1099().getPhone()); |
64 | System.out.println( " Corp name: " + employee[pp].getUS1099().getCorpName()); |
65 | System.out.println( " Corp address: " + employee[pp].getUS1099().getCorpAddress()); |
66 | System.out.println( " Corp relationship: " + employee[pp].getUS1099().getRelationship().toString()); |
70 | System.out.println( "No tax status specified" ); |
76 | System.out.println( "Error! Exception caught" ); |
XML data file: CorporationMegaX.xml
01 | <? xml version = "1.0" encoding = "UTF-8" ?> |
04 | < Name >Corporation MegaX</ Name > |
05 | < Phone >1-800-555-1212</ Phone > |
06 | < Fax >1-877-555-1212</ Fax > |
07 | < Address >512 Megacorp Way, Gotham City</ Address > |
11 | < Employee TaxStatus = "US-W2" Gender = "Male" Desc = "OnSite" > |
12 | < Name >Mr Grand Kahuna</ Name > |
14 | < EmpNumber >1</ EmpNumber > |
15 | < Manager >None</ Manager > |
16 | < YearStart >1998</ YearStart > |
19 | < WorkPhone >1-800-555-1213</ WorkPhone > |
20 | < CellPhone >1-800-555-1214</ CellPhone > |
21 | < Address >100 Cherry Hill Lane, Gotham City</ Address > |
25 | < Employee TaxStatus = "US-1099" Gender = "Male" Desc = "OnSite" > |
26 | < Name >Mr Special Tee</ Name > |
28 | < SsnNumber >123-45-6788</ SsnNumber > |
29 | < Phone >1-817-555-1212</ Phone > |
30 | < CorpName >ABC Consulting</ CorpName > |
31 | < CorpAddress >3 Mockingbird Lane, Smallville AK</ CorpAddress > |
32 | < Relationship >CorpToIndividual</ Relationship > |
35 | < WorkPhone >1-800-555-1215</ WorkPhone > |
36 | < CellPhone >1-800-555-1216</ CellPhone > |
37 | < Address >200 Lookout Hill, Gotham City</ Address > |
41 | < Employee TaxStatus = "US-W2" Gender = "Female" Desc = "OnSite" > |
42 | < Name >Mrs Jenny Reliable</ Name > |
44 | < EmpNumber >2</ EmpNumber > |
45 | < Manager >Mr Grand Kahuna</ Manager > |
46 | < YearStart >1999</ YearStart > |
49 | < WorkPhone >1-800-555-1217</ WorkPhone > |
50 | < CellPhone >1-800-555-1218</ CellPhone > |
51 | < Address >300 Riverside View, Gotham City</ Address > |
Ant build script: build.xml
01 | <? xml version = "1.0" encoding = "utf-8" ?> |
02 | < project name = "IO" default = "compile" basedir = "." > |
03 | < description >Builds, tests, and runs the project Test.</ description > |
04 | < property name = "build.dir" value = "./" /> |
05 | < taskdef name = "xmlbean" classname = "org.apache.xmlbeans.impl.tool.XMLBean" classpath = "/opt/xmlbeans-2.5.0/lib/xbean.jar" /> |
07 | < pathelement location = "/usr/java/latest/lib/tools.jar" /> |
08 | < pathelement location = "/opt/xmlbeans-2.5.0/lib/xbean.jar" /> |
09 | < pathelement location = "./corporation.jar" /> |
11 | < target name = "clean" description = "Remove .class files" > |
12 | < delete includeEmptyDirs = "true" failonerror = "false" > |
13 | < fileset dir = "${build.dir}" > |
14 | < include name = "**/*.class" /> |
18 | < target name = "compile" > |
19 | < javac srcdir = "./" destdir = "./" debug = "true" includeAntRuntime = "false" > |
20 | < classpath refid = "classpath" /> |
21 | < include name = "**/*.java" /> |
24 | < target name = "run" depends = "compile" > |
25 | < java classname = "TestXmlBeans" failonerror = "true" fork = "true" > |
27 | < path refid = "classpath" /> |
Compile: ant compile
[user1@tux XMLBeans]$ ant compile
Buildfile: /home/user1/Desktop/XMLBeans/build.xml
compile:
[javac] Compiling 1 source file to /home/user1/Desktop/XMLBeans
BUILD SUCCESSFUL
Total time: 0 seconds
[Potential Pitfall]:
If you got the following error:
compile:
[javac] Compiling 1 source file to /home/greg/src/Test/JavaXmlBeans
[javac] /home/greg/src/Test/JavaXmlBeans/TestXmlBeans.java:4: error: package noNamespace does not exist
[javac] import noNamespace.RootDocument;
...
...
..
This is due to the XmlBeans JAR file either not being generated or not found in the CLASSPATH. Generate using the command:
scomp -out corporation.jar corporation.xsd
Run: ant run
[user1@tux XMLBeans]$ ant run
Buildfile: /home/user1/XMLBeans/build.xml
compile:
run:
[java] Corporation: Corporation MegaX
[java] There are 3 employees.
[java] Employee name: Mr Grand Kahuna
[java] Gender: Male
[java] Location: OnSite
[java] Cell phone: 1-800-555-1214
[java] Tax status: W2
[java] Employee number: 1
[java] Employee manager: None
[java] Employee start year: 1998
[java] Employee name: Mr Special Tee
[java] Gender: Male
[java] Location: OnSite
[java] Cell phone: 1-800-555-1216
[java] Tax status: 1099
[java] SSN number: 123-45-6788
[java] Phone number: 1-817-555-1212
[java] Corp name: ABC Consulting
[java] Corp address: 3 Mockingbird Lane, Smallville AK
[java] Corp relationship: CorpToIndividual
[java] Employee name: Mrs Jenny Reliable
[java] Gender: Female
[java] Location: OnSite
[java] Cell phone: 1-800-555-1218
[java] Tax status: W2
[java] Employee number: 2
[java] Employee manager: Mr Grand Kahuna
[java] Employee start year: 1999
BUILD SUCCESSFUL
Total time: 1 second
Complex Types with Mixed Content:
Our example is for a standard XML file containing only XML content.
This is common for configuration files.
This is specified in our example by the XML XSD schema:
<xs:element name="US-1099">
<xs:complexType mixed="false">
...
...
</xs:complexType>
One can also have mixed content where there is plain text around the XML content.
The XSD would be stated as:
<xs:element name="US-1099">
<xs:complexType mixed="true">
...
...
</xs:complexType>
and the XML would have plain text mixed with the XML as in this example snippet:
<US-1099>
SSN Number: <SsnNumber>123-45-6788</SsnNumber>
Phone Number: <Phone>1-817-555-1212</Phone>
Corporation: <CorpName>ABC Consulting</CorpName>
Corp Adress: <CorpAddress>3 Mockingbird Lane, Smallville AK</CorpAddress>
Relationship: <Relationship>CorpToIndividual</Relationship>
</US-1099>
XML Beans can handle a complexType with a "mixed" text of both "true" and "false"
with no change to the code.
The same can not be said for JAXB which gets significantly more complex when set to "true".
Links:
YoLinux Tutorials:

Books:
 |
"Core Java 2, Volume 1: Fundamentals "
by Cay S. Horstmann, Gary Cornell
ISBN # 0132354764, Prentice Hall PTR 8th edition
The industry standard. Need I say more?
|
|
 |
"Core Java 2: Volume 2 Advanced Features "
by Cay S. Horstmann, Gary Cornell
ISBN # 0132354799, Prentice Hall PTR 8th edition
The industry standard. Need I say more?
|
|
 |
"Core Java Server Faces"
by David Geary, Cay S. Horstmann
ISBN # 0131738860, Prentice Hall PTR 2nd edition
|
|
 |
"JSP, Servlets, and MySQL"
by David Harms
ISBN # 0764547879, Hungry Minds, Inc
|
|