Wednesday, August 18, 2010

XML To Beans with XMLBeans & Maven Integration

If you have the xsd of the xml you are dealing with (if you do not have it, you have to create it; which is an interface between you and the party giving or consuming the xml) you can easily build java beans from it with xml-beans. Or you can use it to parse easily.

In a project I am dealing, I created a separate artifact which has dependencies to xmlbeans artifacts and I have a plug-in which automatically builds the related beans from xds's under a given directory.

Here are the dependencies for xml-beans:

After adding dependencies as described above add xmlbeans plugin so that related xml's will be created automatically when "mvn install" is executed:

Now you have an artifact which you can add as a dependency. If you add/change an xsd under "src/main/resources/xsd" path with each "mvn install" you will have a jar with beans representing your xmls.

With created beans you can create or parse xml documents easily. First here is an xml how to read a file:

And here is an example for creating a document:

opt stands for the options:

Please note that package name is determined from name space. As you might noticed in creation bean from file example package name was com.yamanyar.ish. This means xsd has following declaration at beginning:

And corresponding xml will like:

I hope this helps.

No comments:

Post a Comment