background image

Basic JAXB Examples

<< PurchaseOrderType Class | Modify Marshal Example >>
<< PurchaseOrderType Class | Modify Marshal Example >>

Basic JAXB Examples

Basic JAXB Examples
This section describes the Basic examples (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 ObjectFactory class 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
Modify Marshal Example
The Modify Marshal example demonstrates how to modify a Java content tree.
1. The
tut-install/javaeetutorial5/examples/jaxb/modify-marshal/src/modifymarshal/Main.java
class declares imports for three standard Java classes plus four JAXB binding framework
classes and primer.po package:
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.*;
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, and po.xml is unmarshalled.
Unmarshaller u = jc.createUnmarshaller();
PurchaseOrder po = (PurchaseOrder)u.unmarshal( new FileInputStream(
"po.xml" ) );
4. set methods are used to modify information in the address branch of the content tree.
USAddress address = po.getBillTo();
address.setName(
"John Bob" );
address.setStreet(
"242 Main Street" );
address.setCity(
"Beverly Hills" );
Basic JAXB Examples
Chapter 17 · Binding between XML Schema and Java Classes
511