Added by Cédric Briançon, last edited by Cédric Briançon on Apr 14, 2008  (view change)

Labels

 
(None)

JAXB provides another alternative to produce XML file, using annotations on Java source code. This process is called "marshalling".
JAXB is also able to do the opposite : from an XML file which represents a Java Object annotated with @XmlRootElement, it can return a Java object for which values are taken from the XML file. This is called "unmarshalling".

Generating XML file

Supposing that we want to get the XML representation of an object filled previously, the marshalling process can be done this way :

final MyObject myObject = new MyObject();
/*
 * Fill here this object with some values, using setters this way :
 * myObject.setMyProperty(myPropertyValue);
 */
final JAXBContext context = JAXBContext.newInstance(MyObject.class);
final Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(myObject, new File("myobject.xml"));

The myobject.xml file should contain the XML representation of this object, if the MyObject class is correctly annotated.

The metadata module of Geotools has been annotated with JAXB in version 2.5, for more explanations on JAXB and the marshalling process, please follow this link : How to generate XML schema from JAXB annotations on the Metadata module

Parsing XML file

To get a Java object from an XML file, you can use the unmarshalling process this way (if the XML file represents an object for which the source code is annotated) : 

final JAXBContext context = JAXBContext.newInstance(MyObject.class);
final Unmarshaller unmarshaller = context.createUnmarshaller();
final MyObject myObject = unmarshaller.unmarshal(new File("myobject.xml"));
/*
 * myObject should contain now values red from the XML file, you can then use getters this way :
 * System.out.println(myObject.getMyProperty());
 */

As said previously, the metadata module of Geotools is annotated since version 2.5 ; we could then use it as following, providing the file in attachement :

final JAXBContext context = JAXBContext.newInstance(MetadataImpl.class);
final Unmarshaller unmarshaller = context.createUnmarshaller();
final Object obj = unmarshaller.unmarshal(new File("jaxb-metadata.xml"));
if (obj instanceof MetaDataImpl) {
    final MetaDataImpl metadata = (MetaDataImpl) obj;
    System.out.println(metadata.getCharacterSet());
    // Other getters ...
}