Friday, October 21, 2016

Convert XML to Objects / XML to Java Classes

Problem : To integrate an external service with your product if all you have is request or response XML. That is in case you dont have WSDL.

How come this problem?
Such a scenario can occur if you want to integrate a service but dont have licence or provide a possible service hook so it can be used during implementation.


Steps 


1. Convert XML to XSD

I used this (http://xmlgrid.net/xml2xsd.html). There was one from freeformatter.com  but it is not able to generate XSD's properly. 

Remember to choose the XML which is most data rich. Of course avoid any error response XMLs.




2. Preprocess XSD

Now, there are problems with the conversion.

a. Remove namespaces in XSD - if you ignore this step, then JAXB will throw error while converting it in next step.

b. Add any datatypes not present in XSD. Every data must have data type associated with it. 

c. Correct the incorrect datatypes as seen in cases of int - They are double. Sometimes DateTime is interpreted as String. 

d. Remove the last character. It cant be recognised -  will show error in Eclipse.



3. Use Eclipse or xfc provided in JDK.

a. Right click the your XSD in eclipse and choose new -> Generate JAXB Classes from Schema.
There are many tutorials (http://www.javawebtutor.com/articles/jaxb/jaxb_java_class_from_xsd.php)

Provide package for the new classes etc. and you are done.

b. Alternatively
you can use xjc utlity . This file comes along with JDK.


xjc  Request.xsd

Generation of separate classes
JAXB will generate a single class with all other classes as nested static classes.

In case you want separate classes for each complex type in XSD then bindings.xsb will come to your rescue. This file tells JAXB to generate separate classes.

Bindings.xjb
<jaxb:bindings
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    version="1.0">
    <jaxb:globalBindings localScoping="toplevel"/>
</jaxb:bindings>

Bindings is an optional file.
xjc -b bindings.xjb  Request.xsd

Another problem I faced was conflicts with naming.

[ERROR] (Relevant to above error) another "MyType" is generated from here.
  line 93 of file:/C:/temp2/Request.xsd
  
  
There were several classes being generated with the same name.
-XautoNameResolution  - will resolve the issue.


xjc -XautoNameResolution -b bindings.xjb  Request.xsd

No comments:

Post a Comment