Difference between revisions of "EclipseLink/Examples/MOXy/JaxbRuntime"
(New page: == Create the JAXB Context (Metadata) == The first thing that needs to be done in an JAXB application is to create the JAXBContext. '''Code Example''' <br>Class[] classes = new Class[4]; ...) |
|||
Line 20: | Line 20: | ||
<br>CustomerType customer = (CustomerType) jaxbElement.getValue(); | <br>CustomerType customer = (CustomerType) jaxbElement.getValue(); | ||
− | == Modify the | + | == Modify the Objects == |
− | Below is an example of manipulating the | + | Below is an example of manipulating the Objects. |
'''Code Example''' | '''Code Example''' | ||
Line 29: | Line 29: | ||
<br>customer.getContactInfo().getPhoneNumber().add(homePhoneNumber); | <br>customer.getContactInfo().getPhoneNumber().add(homePhoneNumber); | ||
− | == Marshal the | + | == Marshal the Objects == |
− | The following code segment demonstrates how to marshal | + | The following code segment demonstrates how to marshal the Objects back to XML. |
'''Code Example''' | '''Code Example''' |
Revision as of 16:00, 22 October 2007
Contents
Create the JAXB Context (Metadata)
The first thing that needs to be done in an JAXB application is to create the JAXBContext.
Code Example
Class[] classes = new Class[4];
classes[0] = AddressType.class;
classes[1] = ContactInfo.class;
classes[2] = CustomerType.class;
classes[3] = PhoneNumber.class;
JAXBContext jaxbContext = JAXBContext.newInstance(classes);
Unmarshal the XML Document
JAXB is used to manipulate XML data. The following code demonstrates how to unmarshal an XML document using the statically generated classes see Generating Java Source from an XML Schema.
Code Example
File file = new File("../Resource/bin/Customer-data.xml");
StreamSource source = new StreamSource(file);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement jaxbElement = unmarshaller.unmarshal(source, CustomerType.class);
CustomerType customer = (CustomerType) jaxbElement.getValue();
Modify the Objects
Below is an example of manipulating the Objects.
Code Example
PhoneNumber homePhoneNumber = new PhoneNumber();
homePhoneNumber.setNumberType("home");
homePhoneNumber.setValue("(613) 555-3333");
customer.getContactInfo().getPhoneNumber().add(homePhoneNumber);
Marshal the Objects
The following code segment demonstrates how to marshal the Objects back to XML.
Code Example
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(jaxbElement, System.out);