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>

Note: If you are using JDK 1.5, then you need to add the javax.xml.bind classes as dependency. Not needed for JDK 1.6.

    <!-- only for JDK 1.5, not required for JDK 1.6 -->
    <dependency>
      <artifactId>jaxb-api</artifactId>
      <groupId>javax.xml.bind</groupId>
      <version>2.1</version>
    </dependency>

    <dependency>
      <artifactId>jaxb-impl</artifactId>
      <groupId>com.sun.xml.bind</groupId>
      <version>2.1.3</version>
    </dependency>

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>

Why do I get Maven jaxb UnmarshalException unexpected element?

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"project"). Expected elements are (none)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:525)
	at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:199)
	at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:194)
	at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:71)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:922)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:366)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:347)
	at com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:99)
	at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:533)
	at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:330)
	at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(XMLNSDocumentScannerImpl.java:779)
	at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(XMLDocumentFragmentScannerImpl.java:1794)
	at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:368)
	at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:834)
	at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
	at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:148)
	at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1242)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:199)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:172)
	at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
	at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:184)
	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.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99)
	at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81)
	at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
	at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75)
	at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45)
	at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:71)
	at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35)
	at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)
	at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
	at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)

Solution

Make sure that correct class is passed to unmarshall.

        javax.xml.bind.JAXBContext jc = javax.xml.bind.JAXBContext
                .newInstance();
        javax.xml.bind.Unmarshaller u = jc.createUnmarshaller();

        JAXBElement<Foo> root = u.unmarshal(new StreamSource(is),
                Foo.class);
        Foo foo = root.getValue();

        return project;
    }

Why do I get "Project not known to this context error"?

javax.xml.bind.JAXBException: Foo is not known to this context
	at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:510)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.getBeanInfo(UnmarshallerImpl.java:502)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:178)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:229)
        ...
	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.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99)
	at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81)
	at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
	at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75)
	at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45)
	at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:71)
	at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35)
	at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)
	at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
	at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)

Solution
Specify the root object when creating the context.

   javax.xml.bind.JAXBContext jc = javax.xml.bind.JAXBContext
                .newInstance(Foo.class);

Reference

Related posts:

  1. Maven FAQ and code snippets for beginners
  2. Access to www.w3.org DTDs blocked from Java
  3. How to copy bean properties with a single line of code
  4. Spring Quartz code snippets for beginners
  5. Maven Docbook for beginners

44 comments to JAXB code snippets for beginners

  • toto

    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 …

  • vineet

    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.

  • John

    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.

  • vineet

    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.

  • John

    Thanks for the quick response Vineet. I tried your pom.xml but am still getting this error.

  • vineet

    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.

  • John

    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

  • John

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

  • vineet

    What result do you get when you type “maven -version”?

  • John

    $ mvn -version
    Maven version: 2.0.7
    Java version: 1.6.0_10
    OS name: “linux” version: “2.6.9-42.elsmp” arch: “i386″

  • vineet

    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.

  • John

    Vineet, what operating system are you using? I tried this on my Mac and Linux box and both are failing for different reasons.

  • vineet

    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.

  • John

    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!

  • vineet

    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.

  • kapil

    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?

  • vineet

    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.

  • Sam

    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?

  • vineet

    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.

  • john-chicago

    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

  • john-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…

  • vineet

    Great. Thanks for posting your solution, hopefully other will find it useful.

  • Anand

    How can set class path for JAXB in XP?

    Please hepl

    regards

    Anand

  • vineet

    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.

  • Anand

    Ok i will try

    Thanks

  • Anand

    i have to finish my work with your help.

    thanks

  • GPS

    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?

  • vineet

    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?

  • GPS

    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.

  • Oscar

    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?

  • Jesus

    Hello, I’m using this plugin to parser multiples xsd files in diferents directories, the only way to do it is with one tag per folder?

  • Michel

    Great article!

    I don’t know what, but something causes the XJC not being executed:
    “Skipped XJC execution. Generated sources were up-to-date.”

    When I delete the “target” directory, only the first schema is parsed and the others are skipped with same message.

    I tried using removeOldOutput, but then all except the first parsing claim “could not delete META-INF/sun-jaxb.episode”.
    I trued using forceRegenerate, which works, but: As I’m using m2eclipse, the generation is executed automatically. Then eclipse detects changes in the xjc folder and causes a rebuild, which again causes the classes to be regenrated and so forth.

    A solution would be disabling auto-build. But that’s not an option for me.
    Another solution would be starting the regenration manually by putting it into a profile and creating a run config, but I’d like to have auto-build.

    Does anyone knows what causes the maven-jaxb2-plugin to think that the classes are up-to-date? Because even when the project is completely checked out by hudson, the classes are not being generated and therefore the build fails (the target folder is NOT in the repo).

  • Thorsten

    Thank you very much, this helped me out of a lot of trouble!

  • Rodrigue

    Hi Vineet,
    just want to thank you for this great job.
    It just helped me out with some problems.
    Thanks

  • Soma Reddy

    I am new to Java and trying to use JAXB to deserialize a simple .xml file. But is giving fits. Here is the exception that I am getting
    Any help is greatly appreciated. Sorry, to post a long message

    ExceptionBegin============================================================================================================================

    javax.xml.bind.UnmarshalException: unexpected element (uri:”", local:”APIWebServicesClientConfig”). Expected elements are (none)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(Unknown Source)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown Source)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown Source)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown Source)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown Source)
    at com.collab.examples.XMLSerializationUtils.DeSerializeFromFile3(XMLSerializationUtils.java:114)
    at com.collab.examples.LoginTF.main(LoginTF.java:132)
    ExceptionEnd==========================================================================================================

    XMLfileBegin===========================================================================================================

    C:\Temp
    V3 1 6 _Open_Issues_SPRs_Latest.xml
    C:\Temp
    APIWebServicesClient1.log
    ProjectForge.mil
    ProjectForge.mil
    5
    proj1077
    tracker1467
    true

    XMLFileEnd=================================================================================

    CodeBegin========================================================================
    public static APIWebServicesClientConfig DeSerializeFromFile3(String pathSpec)
    {

    APIWebServicesClientConfig pDetails = null;

    try
    {
    JAXBContext context = JAXBContext.newInstance(com.collab.examples.APIWebServicesClientConfig.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    pDetails = (APIWebServicesClientConfig) unmarshaller.unmarshal(new File(pathSpec));
    }
    catch (JAXBException ex)
    {
    ex.printStackTrace();

    }
    catch (Exception ex)
    {
    ex.printStackTrace();
    }

    return pDetails;
    }
    CodeEnd====================================================

    APIWebServicesClientConfig.java Begin=================================================================
    package com.collab.examples;
    import java.io.Serializable;
    import javax.xml.bind.*;

    public class APIWebServicesClientConfig implements Serializable {

    // Private members
    private String ArtifactDataFileDir;
    private String ArtifactDataFile;
    private String LogFileDir;
    private String LogFileName;
    private String ProjectForgeContextName;
    private String ProjectForgeServerHost;
    private Boolean UseSSL;
    private Integer TotalNoOfIssuesToBeImported;
    private String TrackerIdTobeUsed;
    private String ProjectId;

    public APIWebServicesClientConfig()
    {

    }
    // Properties
    public String getArtifactDataFileDir()
    {
    return ArtifactDataFileDir;
    }
    public void setArtifactDataFileDir(String ArtifactDataFileDir)
    {
    this.ArtifactDataFileDir = ArtifactDataFileDir;
    }

    public String getArtifactDataFile()
    {
    return ArtifactDataFile;
    }
    public void setArtifactDataFile(String ArtifactDataFile)
    {
    this.ArtifactDataFile = ArtifactDataFile;
    }

    public String getLogFileDir()
    {
    return LogFileDir;
    }
    public void setLogFileDir(String LogFileDir)
    {
    this.LogFileDir = LogFileDir;
    }

    public String getLogfileName()
    {
    return LogFileName;
    }
    public void setLogfileName(String LogFileName)
    {
    this.LogFileName = LogFileName;
    }

    public String getProjectForgeContextName()
    {
    return ProjectForgeContextName;
    }
    public void setProjectForgeContextName(String ProjectForgeContextName)
    {

    this.ProjectForgeContextName = ProjectForgeContextName;
    }

    public String getProjectForgeServerHost()
    {
    return ProjectForgeContextName;
    }
    public String setProjectForgeServerHost(String ProjectForgeServerHost)
    {
    return ProjectForgeContextName;
    }

    public Boolean getUseSSL()
    {
    return UseSSL;
    }

    public void setUseSSL(Boolean UseSSL)
    {
    this.UseSSL = UseSSL;
    }

    public Integer getTotalNoOfIssuesToBeImported()
    {
    return TotalNoOfIssuesToBeImported;
    }

    public String getTrackerIdTobeUsed()
    {
    return TrackerIdTobeUsed;
    }
    public void setTrackerIdTobeUsed(String TrackerIdTobeUsed)
    {
    this.TrackerIdTobeUsed = TrackerIdTobeUsed;
    }

    public String getProjectId()
    {
    return ProjectId;
    }
    public void setProjectId(String ProjectId)
    {
    this.ProjectId = ProjectId;
    }
    }

    APIWebServicesClientConfig.Java End============================================================

  • vineet

    Your XML file did not appear correctly in the comment that you posted.

    Anyway, I think the XML might be invalid. Can you use an XML validation tool (like Eclipse, XMLSpy) or an online tool and confirm if the XML is valid when validated against the schema.

  • Kumar

    Hi Vineet,

    I have limited experience with JAXB, I have an issue which is boggling me for over some time.

    I have a XSD which looks something like this(Forgive my xsd typos, In essence CustomerList can have many customers…) :

    #######################################################################################################################################################################

    ########################################################################################################################################################################

    I use the jaxb2-maven-plugin – xjc goal – to generate the sources

    The generated Class CustomerList.java has @XmlRootElement annotation to it, but the generated class Customer.java has no @XmlRootElement annotation to it.

    Now, get the Customer data in XML in the following sample format :
    ****************************************************************

    Tester
    a
    Interface
    .
    .
    .

    ******************************************************************

    I cannot unmarshall that by providing Customer.java as input to the following code….


    Customer cust =(Customer) EncodeUtils.DecodeString(xmlRequest, Customer.class);

    public static Object DecodeString(String input, Class objectClass)
    throws Exception {

    if (input == null || input.isEmpty()) {
    return null;
    }

    JAXBContext context = JAXBContext.newInstance(objectClass);
    StringReader strReader = new StringReader(input);
    Unmarshaller un = context.createUnmarshaller();
    return un.unmarshal(strReader);
    }

    it would throw up a javax.xml.bind.UnmarshalException: unexpected element (uri:””, local:…. … … error.

    So in essence my req has come down to be able to unmarshal the string the Customer XML to string to Customer.java which doean’t contain @XMLRootElement annotation. If I add that manually the problem is solved, but my use case won’t allow me to do that. Somehow I should be able think of a way programmatically to do that.

    What would be my options to solve the issue(I cannot change the XSD, If I have to I must have a strong argument towards that).

    Any help or input would be greatly appreciated, Although I googled for this, I couldn’t make mush sense of options there.

    Thank you very much. Sorry for the long post.

  • Kumar

    sorry the XML didn’t go through….
    Tester
    a
    Interface

  • Kumar

    Okay fine I will edit the xml it this way .. sorry again..TesteraInterface

  • Narendra Verma

    Hi vineet,

    Nice post you put. I liked it and want to use in my application.
    But when i followed your steps and try to build the project got the below error.

    Could you please help me out?

    Exception:
    ———-

    INFO] The schemaLanguage setting was not defined, assuming ‘AUTODETECT’.
    Using java.util.ServiceLoader
    Cannot find CatalogManager.properties
    [INFO] ————————————————————————
    [INFO] BUILD FAILURE
    [INFO] ————————————————————————
    [INFO] Total time: 0.891s
    [INFO] Finished at: Wed Nov 16 17:46:18 IST 2011
    [INFO] Final Memory: 2M/5M
    [INFO] ————————————————————————
    [ERROR] Failed to execute goal org.jvnet.jaxb2.maven2:maven-jaxb2-plugin:0.7.4:generate (sitemap) on project eating-well: Error parsing the command line [[Ljava.lang.String;@11daa0e]: grammar is not specified -> [Help 1]
    org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.jvnet.jaxb2.maven2:maven-jaxb2-plugin:0.7.4:generate (sitemap) on project eating-well: Error parsing the command line [[Ljava.lang.String;@11daa0e]
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:534)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    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.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
    Caused by: org.apache.maven.plugin.MojoExecutionException: Error parsing the command line [[Ljava.lang.String;@11daa0e]
    at org.jvnet.jaxb2.maven2.RawXJC2Mojo.setupOptions(RawXJC2Mojo.java:487)
    at org.jvnet.jaxb2.maven2.RawXJC2Mojo.doExecute(RawXJC2Mojo.java:250)
    at org.jvnet.jaxb2.maven2.RawXJC2Mojo.execute(RawXJC2Mojo.java:135)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:107)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    … 19 more
    Caused by: com.sun.tools.xjc.BadCommandLineException: grammar is not specified
    at com.sun.tools.xjc.Options.parseArguments(Options.java:809)
    at org.jvnet.jaxb2.maven2.RawXJC2Mojo.setupOptions(RawXJC2Mojo.java:483)
    … 23 more
    [ERROR]
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

  • vineet

    Hi Narendra, what was the exact command line that you used?

  • David Roytenberg

    Thanks for this site. FYI, I tried the workaround described in your December 9th 2009, 5:18 post involving using the JAXBElement and QName classes. Worked very well. Thanks for your trouble.

  • darshan

    Hi Vineet

    This blog is very much helpful for me for maven implementation project from converting ant to maven script.
    This plugin works great but only problem i am facing right now is
    java source file generating from xsd is like this

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = “AccountBaseType”, propOrder = {
    “accountId”,
    “accountSummary”

    but I want to generate like this

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = “AccountBaseType”, namespace = “http://services.com/11/basetypes/account”, propOrder = {
    “accountId”,
    “accountSummary”
    })

    Thanks,
    Darshan

  • darshan

    with namespace declaration

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get Adobe Flash playerPlugin by wpburn.com wordpress themes