Home > Core Java, JAXB > Sample on JAXB using Eclipse

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”>

<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

Advertisement
  1. Johndoe
    September 22, 2010 at 3:11 pm | #1

    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 :D

    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.

    • ®V
      September 22, 2010 at 3:35 pm | #2

      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

  2. Johndoe
    September 23, 2010 at 9:55 am | #3

    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)

  3. Johndoe
    September 23, 2010 at 10:13 am | #4

    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(); …

  4. Hanniebon
    December 20, 2010 at 6:54 pm | #5

    The website https://jaxb-workshop.dev.java.net/plugins/eclipse/xjc-plugin.html appears to be down. Do you have any idea where else the eclipse plug in can be downloaded? Thanks.

  5. bangzippy
    January 8, 2011 at 12:53 am | #6
    • ®V
      January 8, 2011 at 4:38 am | #7

      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

      • Paul
        January 25, 2011 at 3:09 pm | #8

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

      • ®V
        January 26, 2011 at 4:12 am | #9

        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.

  6. Dheeraj
    January 10, 2011 at 6:59 am | #10

    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?

    • ®V
      January 10, 2011 at 7:09 am | #11

      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

  7. Paul
    January 26, 2011 at 12:03 pm | #12

    ®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.

    • ®V
      January 26, 2011 at 3:38 pm | #13

      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

  8. Siv
    February 16, 2011 at 7:05 am | #14

    Hi,

    I cannot find the plugin in the site https://jaxb-workshop.dev.java.net/plugins/eclipse/xjc-plugin.html.

    Also when I download the file from link in your page, I cannot find the folder “org.jvnet.jaxbw.eclipse_1.0.0″.

    Could you please help me on how to install the plugin in eclipse.

    Thanks in advance.

    Siv

    • ®V
      February 19, 2011 at 6:33 am | #15

      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

  9. Raphael
    February 24, 2011 at 3:02 am | #16

    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

    • ®V
      February 25, 2011 at 3:56 pm | #17

      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

  10. Andrei
    May 8, 2011 at 10:47 am | #18

    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.

  11. plamena
    June 13, 2011 at 12:35 pm | #19

    Uhhh this doesn’t work. I’m using Helius

  12. bharathkumar
    September 25, 2011 at 1:22 pm | #20

    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

  13. Shiva
    September 27, 2011 at 12:37 pm | #21

    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……….

  14. February 21, 2012 at 4:33 am | #22

    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

  1. No trackbacks yet.

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 54 other followers