JAXB Part .1 - Marshall a String to an Object / unMarshall an Object to a String

{ Posted on 11:15 AM by Coveted }
When i first started using JAXB in my integration projects. Examples are what helped me the most in understanding how to properly use JAXB in my projects. What i discovered during my searches is the fact that there aren't many good examples to cover all aspects of the process. So i figured I'd add to the library of online examples. So this is part 1 of various installments i'll be doing to cover JAXB.

First up, let's explore the JAVA packages we'll need to import into the class that will be handling the JAXB calls. In this example we'll demonstrate how to use JAXB to unmarshall a String that contains XML that corresponds to a validate XSD Schema that has a JAXB class associated with it.

For this exmaple we'll use this Schema:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://xml.netbeans.org/schema/SimpleString"
xmlns:tns="http://xml.netbeans.org/schema/SimpleString"
elementFormDefault="qualified">
<xsd:element name="simple">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="stringOne" minOccurs="1" maxOccurs="1"/>
<xsd:element name="stringTwo" minOccurs="1" maxOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>


Once a JAXB Binding as been generated within you project using the above XSD. Classes will be generated to be used to access the XML tree elements. The targetNamespace defined within the .XSD will be used to define the package name unless otherwise provided when creating the JAXB binding.

org.netbeans.xml.schema.simplestring.simple;
org.netbeans.xml.schema.simplestring.ObjectFactory;


In this case we will be using "org.netbeans.xml.schema.simplestring.simple" for this example.


1. javax.xml.bind.JAXBContext : This is the class needed to do any marshalling or unmarshalling of Objects and Strings. A JAXBContext will be used to create an instance for handling the class.

Example Code:

import org.netbeans.xml.schema.simplestring.simple;
JAXBContext jbc = JAXBContext.newInstance("simple");


2. Now we will create an unMarshaller instance.
Unmarshaller unmarshaller = jbc.createUnmarshaller();

too be continued...

No Response to "JAXB Part .1 - Marshall a String to an Object / unMarshall an Object to a String"

Post a Comment