JAXB with JDeveloper
Jdeveloper 10g comes with JAXB1.0 tool . This tool makes XML programming just one click away.This tutorial explains using JABX compilation tool of JDeveloper. In previous post we have seen handling of XML schema and XML document . You can refer the same as prerequisite for this post .
Here is the step by step approach
1. Compile xml schema
2. Mention package and Test class
3. This will generate set of java classes under mentioned java package.You will notice one interface and implementation for each complex type or node.
ItemType.java and ItemTypeIMpl.java get generated for complex types ItemType. As we had selected Main class for generation, it creates Main class for testing JAXB compilation.
4. Here is the marshalling and un-marshalling code . [ refer this post for JAXB Coding ]
package jaxb.test;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import jaxb.types.*;
public class Main {
static JAXBContext context = null;
public static void main(String[] args) {
try {
context = JAXBContext.newInstance("jaxb.types");
//Unmarshalling
Unmarshaller um = context.createUnmarshaller();
Order order = (Order) um.unmarshal(new File("D:\\jdev10134\\jdev\\mywork\\JAXBApplication\\JAXBProject\\sample_order.xml"));
System.out.println("Unmarshalling XML -> Java");
System.out.println("Order Id =" + order.getOrderId());
System.out.println("Order Desc = "+order.getOrderDesc());
//marshaling
Marshaller m = context.createMarshaller();
order.setOrderId(02);
order.setOrderDesc("Description has been changed");
System.out.println("MArshalling Java -> XML");
m.marshal(order,System.out);
//m.marshal();
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.toString());
}
}
}
5 . Output will be
Unmarshalling XML -> Java
Order Id =1
Order Desc = First Order
MArshalling Java –> XML
<?xml version = '1.0' encoding = 'UTF-8'?><order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org order.xsd" xmlns="http://www.example.org">
<order_id>2</order_id>
<order_desc>Description has been changed</order_desc>
<ship_to>India</ship_to>
<item_list>
<item>
<item_id>01</item_id>
<item_name>Item-01</item_name>
<item_desc>Item-01 description</item_desc>
</item>
<item>
<item_id>02</item_id>
<item_name>Item-02</item_name>
<item_desc>Item-02 description</item_desc>
</item>
</item_list>
</order>
Yogesh,
ReplyDeleteI have the steps you have mentioned, but I am facing issues while JAXBcompilation, it's not generating the setter method for my list object though it is generating the getter method.
Below is my xsd definition
Can you please help me
Thank you for writingg this
ReplyDelete