background image

JAXBContext instance

<< Unmarshal Real Example | Modify Marshal Example >>
<< Unmarshal Real Example | Modify Marshal Example >>
30
U
SING
JAXB
import javax.xml.bind.Unmarshaller
import primer.po.*;
2. A
JAXBContext
instance is created for handling classes generated in
primer.po
.
JAXBContext jc = JAXBContext.newInstance( "primer.po" );
3. An
Unmarshaller
instance is created.
Unmarshaller u = jc.createUnmarshaller();
4.
po.xml
is unmarshalled into a Java content tree comprising objects gener-
ated by the JAXB binding compiler into the
primer.po
package.
PurchaseOrder po =
(PurchaseOrder)u.unmarshal(
new FileInputStream( "po.xml" ) );
5. A simple string is printed to
system.out
to provide a heading for the pur-
chase order invoice.
System.out.println( "Ship the following items to: " );
6.
get
and
display
methods are used to parse XML content in preparation
for output.
USAddress address = po.getShipTo();
displayAddress(address);
Items items = po.getItems();
displayItems(items);
7. Basic error handling is implemented.
} catch( JAXBException je ) {
je.printStackTrace();
} catch( IOException ioe ) {
ioe.printStackTrace();
8. The
USAddress
branch of the Java tree is walked, and address information
is printed to
system.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");
}