- Forward


Binding XML Schemas to Java Classes with JAXB
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Where We Are:
    • We can manually serialize/deserialize simple objects to/from XML
    • We can use reflection to serialize/deserialize simple objects to/from XML
  • What the Java Architecture for XML Binding (JAXB) Provides:
    • Generates Java classes from XML schemas
    • Create XML documents from simple Java objects (a process they call marshalling to distinguish it from true serialization)
    • Create simple Java objects from XML documents (a process they call unmarshalling to distinguish it from true deserialization)
Data Types
Back SMYC Forward
Schema Type Java Type
xsd:boolean boolean
xsd:byte byte
xsd:dateTime java.util.Calendar
xsd:date java.util.Calendar
xsd:decimal java.math.BigDecimal
xsd:double double
xsd:float float
xsd:int int
xsd:integer java.math.BigInteger
xsd:long long
xsd:short short
xsd:string java.lang.String
xsd:time java.util.Calendar
Generating Java Classes from XML Schemas
Back SMYC Forward

An XML Schema

javaexamples/jaxb/v1/example1.xsd
 
Generating Java Classes from XML Schemas (cont.)
Back SMYC Forward

The Generated Java Code

javaexamples/jaxb/v1/generated/CustomerType.java
 
Generating Java Classes from XML Schemas (cont.)
Back SMYC Forward

The Generated Java Code (cont.)

javaexamples/jaxb/v1/generated/impl/CustomerTypeImpl.java
 
Generating Java Classes from XML Schemas (cont.)
Back SMYC Forward

The Generated Java Code (cont.)

javaexamples/jaxb/v1/generated/ObjectFactory.java
 
Generating Java Classes from XML Schemas (cont.)
Back SMYC Forward

Using the Generated Code

Customer c; ObjectFactory factory; factory = new ObjectFactory(); c = factory.createCustomer();
Unmarshalling (from XML to Java object)
Back SMYC Forward

The XML File

javaexamples/jaxb/Customer.xml
 

The Unmarshalling Process

Customer c; JAXBContext jc; Unmarshaller u; jc = JAXBContext.newInstance(packageName); u = jc.createUnmarshaller(); c = (Customer)u.unmarshal(new FileInputStream(fileName));
Marshalling (from a Java object to an XML file)
Back SMYC Forward

The Marshalling Process

Customer c; JAXBContext jc; Marshaller m; c = new Customer(); // Set and/or modify attributes of c m = jc.createMarshaller(); m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); m.marshal(c, System.out);
There's Always More to Learn
Back -