Pages

Thursday, February 21, 2008

JAXB 2.0 in JDeveloper 10g and 11g

If you know jaxb 1.0 then you know that xjc generates many classes. With the coming of jaxb 2.0 this is a lot less thanks to annotations and the 2.0 version supports now more xml schema types. In this blog I will show how you can use jaxb 2 in JDeveloper 10.1.3 and in 11g and give some tips how to use it.
JDeveloper 10.1.3 supports jaxb 1 and JDeveloper gives you a wizard where can generate the classes by selecting a xml schema. Go for the wizard to the menu tools and then go the jaxb compilation menu item.

If you want to use jaxb 2 then you should read this blog, this explains how to get jaxb 2 support in jdeveloper 10.1.3.
In JDeveloper 11G you can use jaxb 1 and 2. If you do New and go to business tier / toplink jpa then you see the jaxb 1 and 2 options.

If you use JAXB 2.0 Content model from XML schema then we see the following wizard.

Here is some code where I first generate a xml from java then I read this generated xml back in to initialize java objects. I also use the property jaxb.formatted.output to have a nice formatted xml. With the property Marshaller.JAXB_ENCODING I can control the encoding of the xml

DataMessage msg = new DataMessage();
msg.setRecipient("123");
msg.setRecipient("321");
msg.setRunid(run);
msg.setContentlist(conList);

try {
JAXBContext jaxbContext=JAXBContext.newInstance("nl.ordina.mhs");
Marshaller marshaller=jaxbContext.createMarshaller();


File file = new File("c:/temp/1.xml");
marshaller.setProperty("jaxb.formatted.output", true);
marshaller.setProperty( Marshaller.JAXB_ENCODING, "UTF-8" );

marshaller.marshal(msg,file);

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
DataMessage msg2 = (DataMessage) unmarshaller.unmarshal(file);


} catch ( JAXBException e) {
e.printStackTrace();
}

If you use anyType in your schema like this <xs:element name="data" type="xs:anyType"/> You may not be so happy with the jaxb generated code. It generates setData(Object data) The marshaller generates the output of this element not to xml but to text(it converts the xml characters)
You can better change the element to xs:any.
<xs:element name="data">
<xs:complexType>
<xs:sequence>
<xs:any processContents="skip"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Now jaxb generates setData(Data value) where Data is a class where you can set an Element. Now the marshaller generates a nice xml with an embedded xml.

No comments:

Post a Comment