170 likes | 305 Views
Java and XML. Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu HI 96822. Why do we care?. XML is a standard representation for data. We want an efficient and effective way to:
E N D
Java and XML Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu HI 96822
Why do we care? • XML is a standard representation for data. • We want an efficient and effective way to: • Read in XML data and process it using Java. • Write out XML data • Oh, and you will be required to read in XML as part of the DueDates 2.0 assignment. :)
Ways to do this • Read in or write out the XML file as text. • Ridiculous. Don’t even think about it. • Use SAX or DOM or JDOM packages. • OK in some circumstances. • Use JAXB 2.0. • The preferred and easiest approach.
The Approach in a Nutshell • (1) Create an XML “example” file(s) illustrating what your XML data looks like. • (2) Create an XML “schema” that describes the structure of your XML data. • (3) Check your work: Validate the data files against the schema. • (4) Run the JAXB compiler to autogenerate Java classes that represent your XML schema. • (5) Use the JAXB library to read XML data and produce Java instances, or take a Java instance and write it out as XML.
Example: Stack!!!! • Say you have a Stack system and you want to read in a “configuration file” that contains a default stack. • We need to: • Figure out what the XML data looks like. • Figure out the XML schema for this data. • Make sure data is consistent with schema. • Autogenerate the Java classes using JAXB. • Write code to read in the default stack.
Miscellaneous Details • You must download JAXB and define JAXB_HOME • Required so that Ant tasks work. • You do not need an Eclipse classpath var. Why? • Our approach requires two new build files: • validateXml.build.xml • jaxb.build.xml • You will want to exclude JAXB-generated files from Checkstyle, PMD, and FindBugs • Those files are “black boxes” and you do not touch them. • Sample Stack system shows only reading XML. • Writing XML is similarly easy.
Get the source code • Available in stack-johnson/branches/jaxb-example • You can either SVN checkout: • http://stack-johnson.googlecode.com/svn/branches/jaxb-example • Or try the SVN “switch” command to move back and forth between trunk and jaxb-example. • Real SVN Hackers Use Switch. • Use validateXml.build.xml and jaxb.build.xml • You must edit these files slightly to suit your needs!
How to install JAXB • Go to https://jaxb.dev.net/ • Download JAXB RI 2.1.9 (jaxb-2_1_9.zip) • Extract to get jaxb-ri. Rename to jaxb-2.1.9. • Those guys at Sun just don’t get it. • Define JAXB_HOME to point to this directory.