Basic Examples
This section describes the Basic examples (Unmarshal Read, Modify Marshal, Unmarshal Validate) that demonstrate how to:
- Unmarshal an XML document into a Java content tree and access the data contained within it
- Modify a Java content tree
- Use the
ObjectFactoryclass to create a Java content tree from scratch and then marshal it to XML data- Perform validation during unmarshalling
- Validate a Java content tree at runtime
Unmarshal Read Example
The purpose of the Unmarshal Read example is to demonstrate how to unmarshal an XML document into a Java content tree and access the data contained within it.
- The
<INSTALL>/examples/jaxb/unmarshal-read/class declares imports for four standard Java classes plus three JAXB binding framework classes and the
Main.javaprimer.popackage:
import java.io.FileInputStream
import java.io.IOException
import java.util.Iterator
import java.util.List
import javax.xml.bind.JAXBContext
import javax.xml.bind.JAXBException
import javax.xml.bind.Unmarshaller
import primer.po.*;- A
JAXBContextinstance is created for handling classes generated inprimer.po.
JAXBContext jc = JAXBContext.newInstance( "primer.po" );- An
Unmarshallerinstance is created.
Unmarshaller u = jc.createUnmarshaller();po.xmlis unmarshalled into a Java content tree comprising objects generated by the JAXB binding compiler into theprimer.popackage.
PurchaseOrder po =
(PurchaseOrder)u.unmarshal(
new FileInputStream( "po.xml" ) );- A simple string is printed to
system.outto provide a heading for the purchase order invoice.
System.out.println( "Ship the following items to: " );getanddisplaymethods are used to parse XML content in preparation for output.
USAddress address = po.getShipTo();
displayAddress(address);
Items items = po.getItems();
displayItems(items);- Basic error handling is implemented.
} catch( JAXBException je ) {
je.printStackTrace();
} catch( IOException ioe ) {
ioe.printStackTrace();- The
USAddressbranch of the Java tree is walked, and address information is printed tosystem.out.
public static void displayAddress( USAddress address ) {
// display the address
System.out.println( "\t" + address.getName() );
System.out.println( "\t" + address.getStreet() );
System.out.println( "\t" + address.getCity() +
", " + address.getState() +
" " + address.getZip() );
System.out.println( "\t" + address.getCountry() + "\n");
}- The
Itemslist branch is walked, and item information is printed tosystem.out.
public static void displayItems( Items items ) {
// the items object contains a List of
//primer.po.ItemType objects
List itemTypeList = items.getItem();- Walking of the
Itemsbranch is iterated until all items have been printed.
for(Iterator iter = itemTypeList.iterator();
iter.hasNext();) {
Items.ItemType item = (Items.ItemType)iter.next();
System.out.println( "\t" + item.getQuantity() +
" copies of \"" + item.getProductName() +
"\"" );
}Sample Output
Running
java Mainfor this example produces the following output:Ship the following items to: Alice Smith 123 Maple Street Cambridge, MA 12345 US 5 copies of "Nosferatu - Special Edition (1929)" 3 copies of "The Mummy (1959)" 3 copies of "Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora"Modify Marshal Example
The purpose of the Modify Marshal example is to demonstrate how to modify a Java content tree.
- The
<INSTALL>/examples/jaxb/modify-marshal/class declares imports for three standard Java classes plus four JAXB binding framework classes and
Main.javaprimer.popackage:
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import primer.po.*;- A
JAXBContextinstance is created for handling classes generated inprimer.po.
JAXBContext jc = JAXBContext.newInstance( "primer.po" );- An
Unmarshallerinstance is created, andpo.xmlis unmarshalled.
Unmarshaller u = jc.createUnmarshaller();
PurchaseOrder po =
(PurchaseOrder)u.unmarshal(
new FileInputStream( "po.xml" ) );setmethods are used to modify information in theaddressbranch of the content tree.
USAddress address = po.getBillTo();
address.setName( "John Bob" );
address.setStreet( "242 Main Street" );
address.setCity( "Beverly Hills" );
address.setState( "CA" );
address.setZip( new BigDecimal( "90210" ) );- A
Marshallerinstance is created, and the updated XML content is marshalled tosystem.out. ThesetPropertyAPI is used to specify output encoding; in this case formatted (human readable) XML format.
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
m.marshal( po, System.out );Sample Output
Running
java Mainfor this example produces the following output:<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <purchaseOrder orderDate="1999-10-20-05:00"> <shipTo country="US"> <name>Alice Smith</name> <street>123 Maple Street</street> <city>Cambridge</city> <state>MA</state> <zip>12345</zip> </shipTo> <billTo country="US"> <name>John Bob</name> <street>242 Main Street</street> <city>Beverly Hills</city> <state>CA</state> <zip>90210</zip> </billTo> <items> <item partNum="242-NO"> <productName>Nosferatu - Special Edition (1929)</productName> <quantity>5</quantity> <USPrice>19.99</USPrice> </item> <item partNum="242-MU"> <productName>The Mummy (1959)</productName> <quantity>3</quantity> <USPrice>19.98</USPrice> </item> <item partNum="242-GZ"> <productName> Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora </productName> <quantity>3</quantity> <USPrice>27.95</USPrice> </item> </items> </purchaseOrder>Unmarshal Validate Example
The Unmarshal Validate example demonstrates how to enable validation during unmarshalling (Unmarshal-Time Validation). Note that JAXB provides functions for validation during unmarshalling but not during marshalling. Validation is explained in more detail in More About Validation.
- The
<INSTALL>/examples/jaxb/unmarshal-validate/Main.java
class declares imports for three standard Java classes plus seven JAXB binding framework classes and theprimer.popackage:
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.UnmarshalException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.util.ValidationEventCollector;
import primer.po.*;- A
JAXBContextinstance is created for handling classes generated inprimer.po.
JAXBContext jc = JAXBContext.newInstance( "primer.po" );- An
Unmarshallerinstance is created.
Unmarshaller u = jc.createUnmarshaller();- The default JAXB Unmarshaller
ValidationEventHandleris enabled to send to validation warnings and errors tosystem.out. The default configuration causes the unmarshal operation to fail upon encountering the first validation error.
u.setValidating( true );- An attempt is made to unmarshal
po.xmlinto a Java content tree. For the purposes of this example, thepo.xmlcontains a deliberate error.
PurchaseOrder po =
(PurchaseOrder)u.unmarshal(
new FileInputStream("po.xml"));- The default validation event handler processes a validation error, generates output to
system.out, and then an exception is thrown.
} catch( UnmarshalException ue ) {
System.out.println( "Caught UnmarshalException" );
} catch( JAXBException je ) {
je.printStackTrace();
} catch( IOException ioe ) {
ioe.printStackTrace();Sample Output
Running
java Mainfor this example produces the following output: