isusanin asked in the JAXB forum:

When trying to marshall an object I get this error message:

unable to marshal type "org.blah.MessageType" as an element
because it is missing an @XmlRootElement annotation

If I add the @XmlRootElement annotation to the MessageType, it works, but my question is why doesn't the JAXB compiler put this annotation in automatically. It's inconvenient because MessageType is automatically generated and I don't want to edit it every time I regenerate the java classes.

Is there any better way to resolve this problem?

XJC does try to put @XmlRootElement annotation on a class that we generate from a complex type. The exact condition is somewhat ugly, but the basic idea is that if we can statically guarantee that a complex type won't be used by multiple different tag names, we put @XmlRootElement. So for example, if the schema is as follows:


Then you'd get:

class Foo {

But if the schema is as follows, then XJC can't eliminate the possibility that your type might be used in other schemas (that can be compiled separately and put together at runtime):


So you'd get:

class Bar {
class ObjectFactory {
  JAXBElement<Bar> createFoo(Bar value) { ... }

Now, the crucial part in the above inference done by XJC is that "your schema might be used by other schemas that XJC isn't compiling right now". This is certainly true for some users (and we learned that the hard way), but it's also true that for many users this is too conservative an assumption. It's often the case that what you are compiling is indeed the whole thing, and you want XJC to know that so that it can optimize the generated code more aggressively.

Such notion isn't defined in the spec, but as an experiment we have such aggressive optimization mode in XJC, tentatively called "simple-minded binding mode". Consider the following schema that uses this mode (see that <xjc:simple/>customization):


From this you'll just get Foo class, since XJC now knows that only one element is using bar, and therefore there's no point in having two of them around (I just fixed a few issues wrt this, so if you want to try it, wait until tomorrow and download nightly.) Also note that this is an experimental mode and it is subject to change.

Now, that said, there's another way to work around this issue. If all you want is just to marshal an object without @XmlRootElement, then you can just do:

marshaller.marshal( new JAXBElement(
  new QName("uri","local"), MessageType.class, messageType ));