Skip to main content

Notice: This Wiki is now read only and edits are no longer possible. Please see: for the plan.

Jump to: navigation, search


< EclipseLink‎ | Examples‎ | MOXy‎ | GettingStarted
Revision as of 11:37, 25 June 2010 by Unnamed Poltroon (Talk) (Externalized Metadata)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


This example will build upon the lessons learned in the previous example (MOXy Extensions), and demonstrate how the annotations can be expressed as XML. This technique is useful in situations where you are not able to modify the domain objects.

Externalized Metadata

The XML metadata below is equivalent to the metadata represented by the annotations used in the previous example.

<?xml version="1.0"?>
        <java-type name="example.gettingstarted.Customer">
            <xml-type prop-order="name address phoneNumbers"/>
                <xml-element java-attribute="name" xml-path="personal-info/name/text()"/>
                <xml-element java-attribute="address" xml-path="contact-info/address"/>
                <xml-element java-attribute="phoneNumbers" xml-path="contact-info/phone-number"/>
        <java-type name="example.gettingstarted.PhoneNumber">
                <xml-attribute java-attribute="type"/>
                <xml-value java-attribute="number"/>

Converting Objects to XML

The following code is used to convert the objects to XML. Note how the JAXBContext is created using the externalized metadata.

package example.gettingstarted;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class Demo {
    public static void main(String[] args) throws JAXBException {
        // Step 1 - Create the Domain Model
        Customer customer = new Customer();
        customer.setName("Jane Doe");
        Address address = new Address();
        address.setStreet("123 Any Street");
        address.setCity("My Town");
        PhoneNumber workPhoneNumber = new PhoneNumber();
        PhoneNumber cellPhoneNumber = new PhoneNumber();
        // Step 2 - Convert the Domain Model to XML
        Map<String, Source> metadata = new HashMap<String, Source>();
        metadataSourceMap.put("example.gettingstarted", new StreamSource("eclipselink-oxm.xml"));
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap);
        Class[] classes = new Class[1];
        classes[0] = Customer.class;
        JAXBContext jaxbContext = JAXBContext.newInstance(classes, properties);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(customer, System.out);

Back to the top