JAXB code snippets for beginners
What is JAXB
JAXB is a Java library used for reading and writing XML files. Unlike DOM or SAX, JAXB is a high level library that maps XML directly to Java Objects. You point JAXB to an XML file and it returns you a Java object representing the XML. While JAXB is easy to use, it may take some time to get started. I’ve documented everything that you need to know, with code snippets, to help you start using JAXB in a few minutes.
Step 1/2: Mapping your schema XSD to Java
The first step to create Java classes which map to your schema. The XJC compiler does exactly that. Here’s a reference to the XJC compiler. However if you are using Maven, there is a maven jaxb plugin which automatically generates the Java mapping by defining a few snippets in your pom.xml. The following section shows you how to use JAXB from Maven.
Using JAXB from Maven: configure your pom.xml to automatically run the Maven JAXB plugin
To use JAXB from Maven, you need to add the JAXB plugin repository information and the Maven JAXB plugin declaration to your pom.xml.
<pluginRepositories> <pluginRepository> <id>maven2-repository.dev.java.net</id> <name>Java.net Repository for Maven</name> <url>http://download.java.net/maven/2/</url> <layout>default</layout> </pluginRepository> </pluginRepositories>
Change sitemap.xsd below to your schema.xsd name. Also, change the output package “com.vineetmanohar.sitemap.jaxb” to a package of your choice. Generally, this is a brand new package with no other classes in it.
<build>
<plugins>
<plugin>
<!-- jaxb plugin -->
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<executions>
<execution>
<id>sitemap</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<args>
<param>-npa</param>
</args>
<!-- the package for the generated java classes -->
<generatePackage>com.vineetmanohar.sitemap.jaxb</generatePackage>
<npa>true</npa>
<!-- include the following schemas only; by default all *.xsd files are processed -->
<schemaIncludes>
<include>sitemap.xsd</include>
</schemaIncludes>
<!-- whether old output should be removed, this field should generally be set to "true" -->
<removeOldOutput>true</removeOldOutput>
<!-- generate lots of output -->
<verbose>true</verbose>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build
Output and Generated Classes
The JAXB plugin by default runs in the “generate-sources” phase. To run the JAXB plugin, simply run “mvn generate-sources”, or any phase which occurs after “generate-sources”, like “compile”.
mvn compile
This will run the JAXB plugin and generates Java classes for your schema (for sitemap.xsd in the above example). The output java package is “com.vineetmanohar.sitemap.jaxb”, as specified in the plugin configuration above. Here’s how the output looks after running the plugin.
target/generated-sources target/generated-sources/xjc target/generated-sources/xjc/META-INF target/generated-sources/xjc/META-INF/sun-jaxb.episode target/generated-sources/xjc/com target/generated-sources/xjc/com/vineetmanohar target/generated-sources/xjc/com/vineetmanohar/sitemap target/generated-sources/xjc/com/vineetmanohar/sitemap/jaxb target/generated-sources/xjc/com/vineetmanohar/sitemap/jaxb/ObjectFactory.java target/generated-sources/xjc/com/vineetmanohar/sitemap/jaxb/Urlset.java target/generated-sources/xjc/com/vineetmanohar/sitemap/jaxb/TChangeFreq.java target/generated-sources/xjc/com/vineetmanohar/sitemap/jaxb/TUrl.java
Note that the generated classes live in the target directory. You should not modify them or check them into your source control system. These classes are temporary and will be automatically generated when your run maven compile.
Step 2/2: Using the JAXB generated classes from your Java code
Once the code is generated, you are now ready to use the code from your Java class. Here are 3 ways of using JAXB from your java code.
1. Basic way: A basic way is to create a wrapper file which hides all the JAXB details and provides an easy to use interface. See the SitemapJAXBWrapper.java file to see an example implementation. I don’t recommend this option, however, as a beginner you should try it out as it helps you understand the JAXB API. The following option, option #2 is a more preferred approach.
2. Preferred way: This is basically option 1 refactored to hide all the JAXB details. Download this re-usable JAXBWrapper.java class and use that as a wrapper class. The JAXBWrapper class gives you an easy way to do XML to Java and Java to XML conversions in just 2-3 lines of code. All you need to do it pass 2 parameters, the schema URL, and the classes that you want to bind. The classes are the classes that were previously generated using XJC or the Maven JAXB plugin above. In this example we are trying to read a sitemap.xml file and load it into the java class Urlset.java.You won’t find the Urlset.java on my Google Code project because it is a temporary file which is automatically generated when needed and never checked it. Here’s a sample code.
Create a wrapper
JaxbWrapper<Urlset> sitemapJaxbWrapper = new JaxbWrapper<Urlset>(getClass().getResource("/sitemap.xsd"), Urlset.class);
XML to Java
Urlset urlset = sitemapJaxbWrapper.xmlToObject(getClass().getResourceAsStream("/sample-sitemap.xml"));
Java to XML
Urlset urlset = new com.vineetmanohar.sitemap.jaxb.ObjectFactory().createUrlset(); String xml = sitemapJaxbWrapper.objectToXml(urlset);
3. Using Spring framework: The third way to use JAXB is through Spring OXM classes. Here’s a reference documentation. I won’t go into the details, but the idea is that you create a JaxB2Marshaller bean in your spring config, then inject the bean in the class where you want to use it.
FAQ
How to generate classes for multiple schemas in different packages
Add one <execution> step per schema. Add a different <id> per execution. Add a unique <generateDirectory> in the configuration section. By default the <generateDirectory> value is target/generated-sources/xjc. You should set it such that each one of them is different. For example target/generated-sources/xjc1, target/generated-sources/xjc2 etc. Full reference of JAXB configuration is here.
<executions>
<execution>
<id>id1</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<args>
<param>-npa</param>
</args>
<generateDirectory>target/generated-sources/xjc1</generateDirectory>
<generatePackage>some.package1</generatePackage>
<schemaIncludes>
<include>schema1.xsd</include>
</schemaIncludes>
<forceRegenerate>false</forceRegenerate>
<removeOldOutput>true</removeOldOutput>
<verbose>true</verbose>
</configuration>
</execution>
<execution>
<id>id2</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<args>
<param>-npa</param>
</args>
<generateDirectory>target/generated-sources/xjc2</generateDirectory>
<generatePackage>some.package2</generatePackage>
<schemaIncludes>
<include>schema2.xsd</include>
</schemaIncludes>
<forceRegenerate>false</forceRegenerate>
<removeOldOutput>true</removeOldOutput>
<verbose>true</verbose>
</configuration>
</execution>
</executions>
Are JAXB Marshaller and Unmarshaller thread-safe?
No. Marshaller and Unmarshaller are not thread-safe because they use a non-thread safe TransformerFactory. Therefore, you need to create a new Marshaller and Unmarshaller object per invocation. The JAXBWrapper already takes care of that detail.
Why do I get a “unable to marshal type because it is missing an @XmlRootElement annotation]”
If you get this stack trace when running JAXB, see the following solution.
[com.sun.istack.SAXException2: unable to marshal type "org.foo.xmlbindings.FooType" as an element because it is missing an @XmlRootElement annotation] at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:304) at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:230) at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:96) at Caused by: com.sun.istack.SAXException2: unable to marshal type "org.foo.xmlbindings.FooType" as an element because it is missing an @XmlRootElement annotation at com.sun.xml.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:226) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:267) at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:472) at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:301) ... 26 more ... Removed 22 stack frames [com.sun.istack.SAXException2: unable to marshal type "org.foo.xmlbindings.FooType" as an element because it is missing an @XmlRootElement annotation] at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:304) at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:230) at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:96) at Caused by: com.sun.istack.SAXException2: unable to marshal type "org.foo.xmlbindings.FooType" as an element because it is missing an @XmlRootElement annotation at com.sun.xml.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:226) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:267) at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:472) at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:301) ... 26 more ... Removed 22 stack frames
Solution: Make sure that the root element is an anonymous complex type and not an instance of a defined type.
Right root element example:
<xsd:element name="foo">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="bar" type="p:barType" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
Wrong root element example:
<xsd:element name="foo" type="fooType">
</xsd:element>
<xsd:complexType name="fooType">
<xsd:sequence>
<xsd:element name="bar" type="p:barType" />
</xsd:sequence>
</xsd:complexType>
Why do I get Maven Jaxb package-info syntax error
[INFO] Applying extractor for language: java
[INFO] ------------------------------------------------------------------------
[ERROR] FATAL ERROR
[INFO] ------------------------------------------------------------------------
[INFO] syntax error @[8,7] in file:xmlbindings/package-info.java
[INFO] ------------------------------------------------------------------------
[INFO] Trace
com.thoughtworks.qdox.parser.ParseException: syntax error @[8,7] in file:xmlbindings/package-info.java
at com.thoughtworks.qdox.parser.impl.Parser.yyerror(Parser.java:638)
at com.thoughtworks.qdox.parser.impl.Parser.yyparse(Parser.java:747)
at com.thoughtworks.qdox.parser.impl.Parser.parse(Parser.java:619)
at com.thoughtworks.qdox.JavaDocBuilder.addSource(JavaDocBuilder.java:300)
at com.thoughtworks.qdox.JavaDocBuilder.addSource(JavaDocBuilder.java:316)
at com.thoughtworks.qdox.JavaDocBuilder.addSource(JavaDocBuilder.java:312)
at com.thoughtworks.qdox.JavaDocBuilder$1.visitFile(JavaDocBuilder.java:369)
at com.thoughtworks.qdox.directorywalker.DirectoryScanner.walk(DirectoryScanner.java:43)
at com.thoughtworks.qdox.directorywalker.DirectoryScanner.walk(DirectoryScanner.java:34)
at com.thoughtworks.qdox.directorywalker.DirectoryScanner.walk(DirectoryScanner.java:34)
at com.thoughtworks.qdox.directorywalker.DirectoryScanner.walk(DirectoryScanner.java:34)
at com.thoughtworks.qdox.directorywalker.DirectoryScanner.walk(DirectoryScanner.java:34)
at com.thoughtworks.qdox.directorywalker.DirectoryScanner.walk(DirectoryScanner.java:34)
at com.thoughtworks.qdox.directorywalker.DirectoryScanner.walk(DirectoryScanner.java:34)
at com.thoughtworks.qdox.directorywalker.DirectoryScanner.walk(DirectoryScanner.java:34)
at com.thoughtworks.qdox.directorywalker.DirectoryScanner.scan(DirectoryScanner.java:52)
at com.thoughtworks.qdox.JavaDocBuilder.addSourceTree(JavaDocBuilder.java:366)
at org.apache.maven.tools.plugin.extractor.java.JavaMojoDescriptorExtractor.discoverClasses(JavaMojoDescriptorExtractor.java:614)
at org.apache.maven.tools.plugin.extractor.java.JavaMojoDescriptorExtractor.execute(JavaMojoDescriptorExtractor.java:581)
at org.apache.maven.tools.plugin.scanner.DefaultMojoScanner.populatePluginDescriptor(DefaultMojoScanner.java:87)
at org.apache.maven.plugin.plugin.AbstractGeneratorMojo.execute(AbstractGeneratorMojo.java:137)
at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:447)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:539)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:480)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:459)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:311)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:278)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:143)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:333)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:126)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:282)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
[INFO] ------------------------------------------------------------------------
Cause: A file called package-info.java gets generated in the output package. Here's the content of the file.
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.2-b01-fcs // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2008.06.11 at 01:20:24 PM EDT // @javax.xml.bind.annotation.XmlSchema(namespace = "http://www.vineetmanohar.com", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package xmlbindings;
The error is on the period immediately following javax (@javax.)
Workaround: add the no package info generation flag to xjc
<plugin>
<!-- new maven jaxb -->
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<args>
<param>-npa</param>
</args>
Reference
- Official JAXB Maven2 site
- XJC reference
- My open source Google Code project (includes all the code snippents and classes mentioned in this project)
Related posts:

Hi Vineet,
good post. i am interressed by the part you write “The JAXBWrapper already takes care of that detail” on the ThreadSafe part.
When i look to the code you published on http://code.google.com/p/vineetmanohar/source/browse/trunk/src/main/java/com/vineetmanohar/util/JaxbWrapper.java , it seems not so “thread safe”
Maybe i dont understand how it works but with a shared shema and jaxbContext attributes on your jaxbWrapper it seems to me not to be so thread safe …
Hi, thanks for your comment. I’m glad you pointed that out. The JAXBContext class is thread safe and it is ok to share one instance of JAXBContext across multiple threads.
https://jaxb.dev.java.net/guide/Performance_and_thread_safety.html
Similarly, Schema object is an immutable representation of the grammar, it is thread safe and applications are encouraged to share it across many parsers in many threads.
http://java.sun.com/javase/6/docs/api/javax/xml/validation/Schema.html
Both member variables, the JAXBContext and Schema are thread-safe and therefore the JAXBWrapper object is thread safe too.
Hi,
Ran this example but I get the following error
[INFO] Parsing input schema(s)…
[INFO] ————————————————————————
[ERROR] FATAL ERROR
[INFO] ————————————————————————
[INFO] org/relaxng/datatype/ValidationContext
[INFO] ————————————————————————
[INFO] Trace
java.lang.NoClassDefFoundError: org/relaxng/datatype/ValidationContext
at com.sun.xml.xsom.impl.parser.ParserContext.newNGCCRuntime(ParserContext.java:150)
at com.sun.xml.xsom.impl.parser.ParserContext.parse(ParserContext.java:124)
at com.sun.xml.xsom.impl.parser.ParserContext.(ParserContext.java:96)
at com.sun.xml.xsom.parser.XSOMParser.(XSOMParser.java:125)
at com.sun.tools.xjc.ModelLoader.createXSOMParser(ModelLoader.java:420)
at com.sun.tools.xjc.ModelLoader.createXSOMSpeculative(ModelLoader.java:492)
at com.sun.tools.xjc.ModelLoader.loadXMLSchema(ModelLoader.java:366)
at com.sun.tools.xjc.ModelLoader.load(ModelLoader.java:167)
at com.sun.tools.xjc.ModelLoader.load(ModelLoader.java:113)
at org.jvnet.jaxb2.maven2.RawXJC2Mojo.loadModel(RawXJC2Mojo.java:630)
at org.jvnet.jaxb2.maven2.RawXJC2Mojo.doExecute(RawXJC2Mojo.java:258)
at org.jvnet.jaxb2.maven2.RawXJC2Mojo.execute(RawXJC2Mojo.java:134)
at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:443)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:539)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:480)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:459)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:311)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:278)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:143)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:334)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:125)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:280)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Using java version “1.6.0_02″ and Maven version: 2.0.7
Tried running it on JDK 1.5 but got the same error. Please advise on how to fix?
Thanks in Advance.
Try source and target compiler version as 1.6 in the pom.xml.
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
See the full pom.xml.
Thanks for the quick response Vineet. I tried your pom.xml but am still getting this error.
This is most likely a Java version issue. I have:
maven -version
Maven version: 2.0.9
Java version: 1.6.0_10
Try upgrading from 1.6.0_02 to 1.6.0_10 and see if that helps.
Installed 1.6.0_10
All that did was replaced the previous error message with this one
[ERROR] FATAL ERROR
[INFO] ————————————————————————
[INFO] org/apache/maven/shared/io/logging/MessageSink
org.apache.maven.shared.io.logging.MessageSink
[INFO] ————————————————————————
[INFO] Trace
java.lang.NoClassDefFoundError: org/apache/maven/shared/io/logging/MessageSink
at org.apache.maven.plugin.clean.CleanMojo.execute(CleanMojo.java:180)
at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:443)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:539)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:480)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:459)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:311)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:278)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:143)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:334)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:125)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:280)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: java.lang.ClassNotFoundException: org.apache.maven.shared.io.logging.MessageSink
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at org.codehaus.classworlds.RealmClassLoader.loadClassDirect(RealmClassLoader.java:195)
at org.codehaus.classworlds.DefaultClassRealm.loadClass(DefaultClassRealm.java:255)
at org.codehaus.classworlds.DefaultClassRealm.loadClass(DefaultClassRealm.java:274)
at org.codehaus.classworlds.RealmClassLoader.loadClass(RealmClassLoader.java:214)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
… 19 more
Never mind .. it is for maven’s clean. I am still getting the previous error
java.lang.NoClassDefFoundError: org/relaxng/datatype/ValidationContext
I downloaded the jar for relaxngDatatype and manually added to .m2 directory but still no luck
What result do you get when you type “maven -version”?
$ mvn -version
Maven version: 2.0.7
Java version: 1.6.0_10
OS name: “linux” version: “2.6.9-42.elsmp” arch: “i386″
FYI: If I run a fresh install, I see this on my output:
Downloading: http://download.java.net/maven/1/relaxngDatatype/poms/relaxngDatatype-20020414.pom
Downloading: http://repo1.maven.org/maven2/relaxngDatatype/relaxngDatatype/20020414/relaxngDatatype-20020414.pom
Also, my maven version is 2.0.9. Not sure if it matters, but you’re desperate give that a try.
Have you tried running my Google Code project, as is:
svn checkout http://vineetmanohar.googlecode.com/svn/trunk/ vineetmanohar-read-only
mvn clean test
See if that helps. It worked for me with my maven version and java version, and starting with an empty .m2 directory.
Vineet, what operating system are you using? I tried this on my Mac and Linux box and both are failing for different reasons.
I use both Mac and Linux, works for me on both. Sorry, I am unable to replicate your issue. Try searching for “java.lang.NoClassDefFoundError: org/relaxng/datatype/ValidationContext” on google. You will see many posts which indicate that this might be related to JVM version. It makes sense too, as Java is the only variable from one environment to the other – other dependencies are controlled by Maven.
If you have multiple java versions installed, “mvn -version” will tell you which version is being used by maven. You can change that version by setting JAVA_HOME.
I tried different java versions. Unfortunately, couldn’t make it to like me.
I needed this for a quick XSD -> POJO conversion and couldn’t spend any more time on it. So I downloaded Eclipse JAXB plugin and got what I needed
Thanks for all the feedback!
I’ll post back if I find the answer to your problem. In the meantime, you should still be able to use the JAXBWrapper class as described in the blog post. You can point it to your XML file and it returns you the POJO (that you generated using Eclipse JAXB). It creates JAXBContext, Marshaller, Unmarshaller classes in a thread-safe way and also does schema validation.
I am trying to marashall data from 3 different beans into a single xml file. I thought I would use JAXB to accomplish that. I am novice when it comes to using JAXB. This is companies work. Can you please help me out?
Assuming that you have an XSD for your target XML, you should first generate JAXB objects as described in the article. Next, manually convert your 3 beans to the JAXB object in Java code and then call objectToXml() method on the JAXBWrapper class.
Hi,
If I don’t have access to edit the schema file and run into this error: “unable to marshal type because it is missing an @XmlRootElement annotation]”, what is the workaround?
I have never tried it, but there are 2 options described in this post that you can try.
http://weblogs.java.net/blog/kohsuke/archive/2006/03/why_does_jaxb_p.html
Another simpler solution is to create a copy of the original schema and redefine the root element and use this copy with JAXB. The downside is that you will have to sync your copy everytime the original schema changes, so this approach is practical only if the original schema is not expected to change often.
I too ran into the same problem as John with the “NoClassDefFoundError: org/relaxng/datatype/ValidationContext” problem. i started with my maven 2.2.1 then backed off to maven 2.0.7 – which sounds crazy to me. but i got the same “NoClassDefFoundError: org/relaxng/datatype/ValidationContext” with another clean/install. i tried it against your google project. same result.
the last time i looked over this, it DID work on a hard drive which used jdk1.6.0_04.
Maven version: 2.0.7
Java version: 1.6.0_17
OS name: “windows vista” version: “6.0″ arch: “x86″
i am presently using the following from mvn – version
the cxf-codegen-plugin from http://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html DOES work
and a good old command xjc works as well
any ideas on the maven problems??
thanks
john from chicago
well mystery solved for now
after updating the entire Subversion configuration of
org.jvnet.jaxb2.maven2
maven-jaxb2-plugin
from https://maven-jaxb2-plugin.dev.java.net/source/browse/maven-jaxb2-plugin/
and after uninstalling my maven’s jar of ralaxngDatatype and
with using this configuration on my machine:
Maven version: 2.0.7
Java version: 1.6.0_17
OS name: “windows vista” version: “6.0″ arch: “x86″
maven-jaxb2-plugin now DOES work. i ran the test files that came with the subversion update
and i ran your own google example.
i surmise that i had a “bad” copy of ralaxngDatatype from somewhere…
Great. Thanks for posting your solution, hopefully other will find it useful.
How can set class path for JAXB in XP?
Please hepl
regards
Anand
In Maven, you can use the <dependencies> tag inside the <plugin> declaration for the JAXB plugin. For runtime classpath, you can use the <dependencies> tag of the <build> tag. Hope that helps.
Ok i will try
Thanks
i have to finish my work with your help.
thanks
I am gonna use JaxB for the first time… I created a maven project and added the source schema under resources. However, I am not able to import ObjectFactory somehow after maven clean compile install… When I manually add the jar created in the last step in the class path, its getting resolved and ObjectFactory is being recognized.
Is this how its supposed to be?
No, you should not add the jars manually to the classpath – the maven JAXB plugin should do that automatically. It should add the ‘target/generated-sources’ directory as a source directory in maven, and therefore all java files generated there should be automatically part of your classpath. Does the example posted in the blog work for you?
I didn’t try the example posted here, but I know now why if didn’t work in my case. I actually created 2 projects, one only for generating target, and other one, which would use the jar created in first one, and forgot to add 1st one’s jar dependency in 2nd one’s Pom. That’s why it was not picking up and I was adding manually in classpath. Once I have some more detailed handson, will try the example posted here.
Hello, your blog is very helpful, here is a question, I have an entity, with an @override toString() method, and i want to keep it as it is into the created classes, is there any way to do that? any plug in or argument?