The XML Marshaller API
{@link org.exolab.castor.xml.Marshaller} marshalls a Java object into an XML document. {@link org.exolab.castor.xml.Unmarshaller} unmarshalls an XML document back into a Java object.
The following example unmarshals the XML document product.xml into a Product object, performs simple changes to the object and then marshals it back into an XML document.
Product prod; File file; file = new File( "product.xml" ); // Unmarshal the document into an object prod = (Product) Unmarshaller.unmarshal( Product.class, new FileReader( file ) ); // A 25% mark down for each product and mark as sale prod.markDown( 0.25 ); prod.setOnSale( true ); // Marshal the object into a document Marshaller.marshal( Product, new FileWriter( file ) );
In addition to static methods, marshaller objects can be created and set with a variety of options affecting how they will operation. The above example adapted to use a specific mapping file:
Mapping map; Unmarshaller umr; Marshaller mar; // Load the specified mapping file map = new Mapping(); map.loadMapping( "mapping.xml" ); // Unmarshal the document into an object umr = new Unmarshaller( Product.class ); umr.setMapping( mapping ); prod = (Product) umr.unmarshal( new FileReader( file ) ); : : : // Marshal the object into a document mar = new Marshaller( new FileWriter( file ) ); mar.setMapping( mapping ); mar.marshal( Product );