Sample on JAXB using Eclipse

Java Architecture for XML Binding (JAXB) allows Java developers to map Java classes to XML representations.

JAXB provides two main features:

1. The ability to marshal Java objects into XML

2. To unmarshal  XML back into Java objects.

In other words, JAXB allows storing and retrieving data in memory in any XML format, without the need to implement a specific set of XML loading and saving routines for the program’s class structure. It is similar to xsd.exe and xmlserializers in .Net Framework.

JAXB is particularly useful when the specification is complex and changing. In such a case, regularly changing the XML Schema definitions to keep them synchronised with the Java definitions can be time consuming and error prone.

Follow the steps to configure and Test JXB Sample project in Eclipse.

1. Install Eclipse plug-in for JXB2.0 https://jaxb-workshop.dev.java.net/plugins/eclipse/xjc-plugin.html
or click on the link to download jaxb-xjc(rename the “docx” extension  2 “jar”)

2. Once download extract the Zip file and copy the folder “org.jvnet.jaxbw.eclipse_1.0.0” into the home directory of Eclipse > plug-in

3. Re-start the Eclipse, if the plug-in doesn’t appear then simple run the “eclipse.exe -clean” option.

4. Now create one project SampleJXB and inside the java source folder create a package like “com.mytest.jxb”

5 Add one XSD with below contents.

<?xml version=”1.0″ encoding=”utf-16″?>

<xsd:schema attributeFormDefault=”unqualified” elementFormDefault=”qualified” version=”1.0″ xmlns:xsd=”http://www.w3.org/2001/XMLSchema”&gt;

<xsd:element name=”persons” />

<xsd:complexType name=”itemsType”>

<xsd:sequence>

<xsd:element maxOccurs=”unbounded” type=”itemType” />

</xsd:sequence>

</xsd:complexType>

<xsd:complexType name=”itemType”>

<xsd:sequence>

<xsd:element name=”firstname” />

<xsd:element name=”lastname” />

<xsd:element name=”email” />

</xsd:sequence>

</xsd:complexType>

</xsd:schema>

6 Now right click on the XSD file and choose JAXB 2.0 -> Run XJC

7 You will be prompted for package name and output directory in the wizard. Simple add the package name given in step 4 and follow the rest of steps.

8 Now navigate to the java package, You will notice 3 classes got generated after running the JAXB command

1. ItemsType.java

2. ItemType.java

3. ObjectFactory.java

9 Now write one Java class to interact with JAXB

import java.io.FileOutputStream;

import java.io.InputStream;

import java.util.List;

import javax.xml.bind.JAXBContext;

import javax.xml.bind.JAXBElement;

import javax.xml.bind.JAXBException;

import javax.xml.bind.Marshaller;

import javax.xml.bind.Unmarshaller;

public class PersonListManager {

private JAXBContext jaxbContext = null;

private Unmarshaller unmarshaller = null;

private ItemsType items = null;

public PersonListManager() {

try {

jaxbContext = JAXBContext.newInstance(“com.mytest.jxb”); //MAKE SURE THE SAME PACAKGE NAME GIVEN IN STEP 4

unmarshaller = jaxbContext.createUnmarshaller();

} catch (JAXBException e) {

}

}

public List loadXML(InputStream istrm) {

try {

Object obj = unmarshaller.unmarshal(istrm);

if(items == null) {

items = (ItemsType)(((JAXBElement)obj).getValue());

return(items.getItem());

}

} catch (JAXBException e) {

e.printStackTrace();

}

return null;

}

/**

* This method will write back to the XML

* @param xmlName

* @throws Exception

*/

public void writeDataInXML(String xmlName) throws Exception{

/* Make sure ItemsType should have @XmlRootElement(name=”items”)if missing add */

ObjectFactory factory= new ObjectFactory();

ItemsType persons = factory.createItemsType();

ItemType item = factory.createItemType();

item.setFirstname(“xyz”);

item.setLastname(“jkl”);

item.setEmail(“anyemail@aa123.com”);

persons.getItem().add(book1);

Marshaller marshaller =jaxbContext.createMarshaller();

marshaller.marshal(library, new FileOutputStream(xmlName)) ;

}

}

10. Now write one more Java class to test the JAXB.

public class TestJAXB {

public static void main(String[] args) {

PersonListManager xmgr = new PersonListManager();

File file = new File(“NewXMLSchema.xml”);

List lst = new ArrayList();

try {

FileInputStream fis = new FileInputStream(file);

lst = xmgr.loadXML(fis);

Iterator<ItemType> lst = rtList.iterator();

while(lst.hasNext()){

ItemType item = lst.next();

System.out.println(“First Name = ” + item.getFirstname().trim() +

“\t\tLast Name = ” + item.getLastname().trim() +

“\t\tEmail = ” + item.getEmail().trim());

}

//xmgr.writeDataInXML(“NewXMLSchema.xml”);

} catch (FileNotFoundException e) {

e.printStackTrace();

}catch(Exception e){

e.printStackTrace();

}

}

}


Thanks
R Vashi

Advertisements

26 thoughts on “Sample on JAXB using Eclipse

  1. Johndoe

    Hi!
    This is my first contact with JaxB AND Java. I am trying to learn things simoultaneously and in a short time so please bare with me a bit 😀

    Well, Eclipse produced errors with a lot of stuff (ok mainly the quotes) which I resolved, but there is a crucial error that I cant fix, more because I dont quite understand what this line does :
    Iterator lst = rtList.iterator();
    Eclipse sais that rtList cannot resolved and “duplicate local variable lst”
    Moreover it prompts that List is a raw type and references to it should be parametrized.
    Could you please enlighten me? It is only a week now that I ve been learning java and eclipse and tons of stuff and at some points I feel a bit overwhelmed.

    Reply
    1. ®V Post author

      Hi John
      never worries mate,

      For the first error “rtList ” check that might be declared twice. Remove the duplicate declaration.

      And for the second it is not the error but a warning given by the compiler to parametrize the object. as since jdk1.5 all the collection objects are typesafe because of java generics implementations. Simply add the object name to the collection object.

      I.e. List<MyBean> objList = new ArrayList<MyBean>();

      There is one more advantage of parametrize,that you don’t have to typecast the object during iteration.

      Please let me know if it solve your issue.

      Thanks
      R vashisht

      Reply
  2. Johndoe

    Ok thanks so much, I solved the problem with the list array. The rtList though insists and it is not declared twice :S

    A million thanks for your swift answers..
    (I know my questions are silly but I am actually a Matlab guy who suddenly has to make MANY things work in Java)

    Reply
  3. Johndoe

    OK found it!! hopefully I solved it correctly..
    If I understood what was wrong, we should declare an iterator on the lst list so the solution that produced no errors was :

    Iterator it = lst.iterator();

    while(it.hasNext()){

    ItemType item = it.next(); …

    Reply
    1. ®V Post author

      Hi Bangzippy,

      i think they have removed the plugin.. let me find it for you.. will post the zip to download here…
      many thanks for your feedback.

      Thanks
      Admin

      Reply
      1. Paul

        Um, I’m looking for this plugin too. If you have it somewhere and could post it, I’d really appreciate it. Thank you.

      2. ®V Post author

        hi Paul,

        It is already given there a link to download the plugin jar file, simply download that and copy it in plugins folder under eclipse.
        search for the below line on the same post.. those contains a link of the jar file.

        “1. Install Eclipse plug-in for JXB2.0 https://jaxb-workshop.dev.java.net/plugins/eclipse/xjc-plugin.html
        or jaxb-xjc(rename the “docx” extension 2 “jar”)”

        let me know if you still facing any issues.

  4. Dheeraj

    vashisht,
    I have a small challenge in JAXB integeration, We have a interface which Maps a flat file and store to database which was done using JAXB,
    Is there any way that we can trigger an email notificaton for users, if the fields are not matched up rightly?

    Reply
    1. ®V Post author

      hi Dheeraj,

      Could you paste a snippet of your flat file.. and some info about the fields.. for quicker thing while unmarshling you can while handling the exception can send the notification to the users by email.. all the errors related with XML to java objects mapping and vice-versa got raised while marshaling and unmarshling of the objects using JAXB. Also go through with the types of exceptions being raised while transformation.. that would be a good candidate for you achieve the required..


      Thanks
      Admin

      Reply
  5. Paul

    ®V :
    hi Paul,
    It is already given there a link to download the plugin jar file, simply download that and copy it in plugins folder under eclipse.
    search for the below line on the same post.. those contains a link of the jar file.
    “1. Install Eclipse plug-in for JXB2.0 https://jaxb-workshop.dev.java.net/plugins/eclipse/xjc-plugin.html
    or jaxb-xjc(rename the “docx” extension 2 “jar”)”
    let me know if you still facing any issues.

    As you notice, I responded to a prior post from bangzippy saying that the target of the link was not found. It is still not found. You provided the same link. I assumed that your comment to bangzippy meant that there was a link that actually worked rather than a copy of the same link that still doesn’t have anything on the end of it. Is there such a link? Thanks for the help.

    Reply
    1. ®V Post author

      HI Paul,

      you don’t need to go to that site anymore i have given a link to download the jar file in my post itself, just read my post carefully you will see a link to download the jar file.
      hope this helps.

      thanks
      admin

      Reply
    1. ®V Post author

      HI Siv,

      you simply download the docx file from the link I have given. Just rename that to jar extension and copy and paste that into plugin folder of you eclipse version.
      just restart the eclipse with “-clean” option. YOu will see an option for JAXB whenever you right click on XSD file.

      HTH

      Thanks
      RVashi

      Reply
  6. Raphael

    Hi,

    Which version of Eclipse you are using. I installed the plugin to my Eclipse 3.5.2 distribution, run “eclipse -clean” as you said, but the plugin still not appear. Would you please help.

    Thanks

    Raphael

    Reply
    1. ®V Post author

      Hi,

      Please try the below link to download the plugin.
      http://sourceforge.net/projects/jaxb-builder/

      After download, follow the below steps.
      1.It includes a JAXB project wizard,
      2. JAXB builder and property pages for JAXB configuration.
      3. Create a JAXB project from the Java project group.
      4 The project wizard creates the following directories:
      schema : place your .xsd files here.
      jaxb : the plugin will generate java source into this directory
      bin : the plugin will place compiled source into this directory

      Once you copy your XSD files in schema folder, Go to Project Menu-> Clean-> <>(to build)

      And you will notice the generated Java code in “src” folder.

      IMPORTANT : Make sure you choose the Java XML Binding Project Project from the Wizard(JAXB)

      Hope this helps.

      BTW I have used on Eclipse 3.2,


      Thanks
      R Vashi

      Reply
  7. Andrei

    Hi,

    In Helios the plugin does not make the JAXB2.0 entry in the right click menu. You need to create a new Java Binding Project copy the .xsd there and right click-> Generate-> JAXB Classes.

    Sadly that did not work 😦 -> exception

    BUT! if you create a package inside the Binding project\jaxb then copy the xsd to it–> the project generates the classes automatically in a default package. If you remove the xsd it will also remove the generated classes.

    Reply
  8. bharathkumar

    hi i am trying to intall plugin as you said but its not appeared after restart the eclipse also.
    i am using eclipse helios.here what i am doing means that “what you given file inthe form of docx” that file save it with extension jar and paste that jar in my eclipse plugin folder is it correct way or not please help me.

    thanking you
    bbharath025@gmail.com

    Reply
  9. Shiva

    hi,
    i written this schema in eclipse galileo 3.x somthing

    after writing this right click and i given package but i didn’t get java classes related to schema……….

    Reply
  10. vst rao

    Hello, I am trying on Eclipse galilio version but no luck yet. I restarted with -clean option but I am not getting JAXB20 -> class option under right click. Any help is greatly appreciated

    Reply
  11. Arindam Gupta

    I am using the JAXB 2.1 plugin – I am encountering an interesting issue – this may have been discussed on this forum before but if someone can help that will be great.

    This is got to do with the schema design and the corresponding Java code that is being generated.

    1. Say I have a complexType called “DEALBASE”. Now I expose it as a root element with the following declaration – – this is valid schema and duly validated by XMLSpy.When I compile the schema I am noticing that the DEAL class that is being generated does not have the @XmlRootElement annotation and at run time fails to unmarshall the XML document. If however I define the DEAL element like this –

    then the DEAL class gets generated with the @XmlRootElement tag and works just fine.
    So what is going on here? Both are valid schemas – why does the compiler behave differently? Any help is very much appreciated.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s