background image

JAXB Examples Output

<< Modify Marshal Example | Unmarshal Validate Example >>
<< Modify Marshal Example | Unmarshal Validate Example >>
32
U
SING
JAXB
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" );
address.setState( "CA" );
address.setZip( new BigDecimal( "90210" ) );
5. A
Marshaller
instance is created, and the updated XML content is mar-
shalled to
system.out
. The
setProperty
API 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 Main
for 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>