The Java EE 5 Tutorial

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/ class declares imports for three standard Java classes plus four JAXB binding framework classes and primer.po package:

    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 marshalled 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 );

Building and Running the Modify Marshal Example Using NetBeans IDE

Follow these instructions to build and run the Modify Marshal example on your Application Server instance using the NetBeans IDE.

  1. In NetBeans IDE, select File->Open Project.

  2. In the Open Project dialog, navigate to tut-install/javaeetutorial5/examples/jaxb/.

  3. Select the modify-marshal folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click the modify-marshal project and select Run.

Building and Running the Modify Marshal Example Using Ant

To compile and run the Modify Marshal example using Ant, in a terminal window, go to the tut-install/javaeetutorial5/examples/jaxb/modify-marshal/ directory and type the following:

ant runapp