Scrivio Interview library
ConceptIntermediate6 min read · updated 12 November 2026

When does xjc generate classes without @XmlRootElement, and how do you marshal and unmarshal such types using JAXBElement?

xjc puts @XmlRootElement on a generated class only when a global element is declared with an anonymous complex type, because then the class and the element are one thing. When a global element refers to a named complex type, the type could be used by several elements, so xjc generates the class without a root annotation and adds a factory method in ObjectFactory that returns JAXBElement<T>. We marshal such types by wrapping them in a JAXBElement, through new JAXBElement<>(qname, type, value) or objectFactory.createOrder(value), and unmarshal with unmarshal(source, OrderType.class).getValue().

Why this question is asked

Many developers meet JAXBElement for the first time when they generate classes from a partner's XSD, try to marshal one, and get an error saying the class is missing an @XmlRootElement annotation. The reaction is often to add the annotation by hand to generated code, which is overwritten at the next build. Interviewers ask this concept question to see whether we understand the schema rule behind xjc's choice and the standard way to work with it. In this answer, we will recap the two kinds of schema declarations, see exactly when xjc adds the root annotation, and then marshal and unmarshal such types with JAXBElement, including the cases where JAXBElement carries information a plain object cannot.

1A Quick Recap: Elements and Types in XML Schema

An XML Schema separates two ideas. A type describes a shape: which child elements and attributes something has. An element is a name that can appear in a document, and every element has a type. A global element, declared directly under xs:schema, may be used as the root of a document.

A schema can describe the type of a global element in two ways. It can define the type inline, without a name, inside the element declaration; that is called an anonymous complex type. Or it can refer to a named complex type defined elsewhere in the schema with type="tns:OrderType". The difference looks cosmetic, but it changes what xjc generates.

XML
<!-- Anonymous type: the type exists only for this element -->
<xs:element name="invoice">
<xs:complexType>
<xs:sequence><xs:element name="number" type="xs:string"/></xs:sequence>
</xs:complexType>
</xs:element>
<!-- Named type: reusable, and here used by two global elements -->
<xs:complexType name="OrderType">
<xs:sequence><xs:element name="id" type="xs:string"/></xs:sequence>
</xs:complexType>
<xs:element name="order" type="tns:OrderType"/>
<xs:element name="cancelOrder" type="tns:OrderType"/>

2When xjc Adds @XmlRootElement

For the invoice element, the anonymous type belongs to exactly one element. xjc generates a class Invoice and can safely say that an Invoice object always means an <invoice> element, so it adds @XmlRootElement(name = "invoice").

For OrderType, that is not true. The same class is the type of <order> and of <cancelOrder>, and it may also be used for local elements inside other types. If xjc put @XmlRootElement(name = "order") on OrderType, then marshalling an OrderType meant for a cancellation would wrongly produce <order>. So xjc leaves the class without a root annotation, and instead generates one method per global element in ObjectFactory, each annotated with @XmlElementDecl, which records the element name and returns a JAXBElement<OrderType>.

Java
// Generated by xjc
@XmlRootElement(name = "invoice")
public class Invoice { protected String number; }
@XmlType(name = "OrderType", propOrder = {"id"})
public class OrderType { protected String id; } // no @XmlRootElement
@XmlRegistry
public class ObjectFactory {
private static final QName _Order_QNAME = new QName("urn:acme:orders", "order");
private static final QName _CancelOrder_QNAME = new QName("urn:acme:orders", "cancelOrder");
@XmlElementDecl(namespace = "urn:acme:orders", name = "order")
public JAXBElement<OrderType> createOrder(OrderType value) {
return new JAXBElement<>(_Order_QNAME, OrderType.class, null, value);
}
@XmlElementDecl(namespace = "urn:acme:orders", name = "cancelOrder")
public JAXBElement<OrderType> createCancelOrder(OrderType value) {
return new JAXBElement<>(_CancelOrder_QNAME, OrderType.class, null, value);
}
}
Step throughHow xjc decides
  1. Read a global xs:element
  2. Is its type anonymous (defined inline)?
    YesClass gets @XmlRootElementNoClass has no root annotation
  3. For a named type, add an ObjectFactory method@XmlElementDecl, returns JAXBElement<T>
  4. Marshal or unmarshal through JAXBElementit carries the element name

4 steps in order. Play them, or step through them one at a time.

The root annotation is only safe when one class always means one element.

3Marshalling With JAXBElement

A JAXBElement is a small wrapper holding three things: the element name as a QName (namespace and local name), the declared type, and the value. Marshalling a bare OrderType fails because JAXB has no element name for it; wrapping it supplies the name.

Java
OrderType order = new OrderType();
order.setId("A-17");
Marshaller m = ctx.createMarshaller(); // ctx = JAXBContext.newInstance(ObjectFactory.class)
m.marshal(order, System.out);
// MarshalException: unable to marshal type "OrderType" as an element because it is missing an @XmlRootElement annotation
ObjectFactory of = new ObjectFactory();
m.marshal(of.createOrder(order), System.out);
// <ns2:order xmlns:ns2="urn:acme:orders"><ns2:id>A-17</ns2:id></ns2:order>
m.marshal(of.createCancelOrder(order), System.out);
// <ns2:cancelOrder xmlns:ns2="urn:acme:orders"><ns2:id>A-17</ns2:id></ns2:cancelOrder>
// Without ObjectFactory: build the wrapper directly
m.marshal(new JAXBElement<>(new QName("urn:acme:orders", "order"), OrderType.class, order), System.out);

Notice that the same object is written as two different documents depending on the wrapper. That is exactly the situation that made xjc refuse to add a root annotation. ObjectFactory methods are the safer choice, because their QNames come from the schema and cannot be mistyped.

4Unmarshalling and Reading the Element Name

When we unmarshal a document whose root is a JAXBElement-declared element, unmarshal(source) returns a JAXBElement, not the bare object, which surprises people who cast the result straight to OrderType. The cleaner way is to pass the expected type, which always returns a JAXBElement<OrderType>.

Java
Unmarshaller u = ctx.createUnmarshaller();
Object raw = u.unmarshal(new StringReader(xml));
raw.getClass(); // class jakarta.xml.bind.JAXBElement, not OrderType
OrderType o1 = (OrderType) JAXBIntrospector.getValue(raw); // unwraps either form
JAXBElement<OrderType> el = u.unmarshal(new StreamSource(new StringReader(xml)), OrderType.class);
el.getName().getLocalPart(); // "cancelOrder": we know which element it was
OrderType o2 = el.getValue();

The element name is real information here. If the same type arrives as either <order> or <cancelOrder>, the name is what tells us whether to create or cancel, so throwing the wrapper away too early can lose meaning.

JAXBElement also carries nil. A nillable element that arrives as <order xsi:nil="true"/> unmarshals to a JAXBElement whose isNil() is true and whose value is null. A plain field could not tell 'element absent' from 'element present but nil', which is why xjc sometimes generates JAXBElement<String> fields for nillable optional elements inside classes too.

5Can We Get Root Annotations Anyway?

Yes, through binding customisations, but they are a choice, not a fix. xjc's simple binding mode, enabled with the xjc:simple customisation in a binding file, and community plugins that annotate generated classes can add @XmlRootElement to classes of named types when each type is used by one element (check what your plugin and version support). Both make code a little shorter. But when one type serves several elements, no annotation can be correct for all of them, and the JAXBElement approach is the standard, portable way. Hand-editing generated sources is never the answer, since the next build overwrites them.

6Follow-up questions

Why does my JAXBContext not know the root elements?

Root element declarations from @XmlElementDecl live in ObjectFactory. If the context is created from OrderType.class alone, it never sees them. Create it from ObjectFactory.class or from the package name so the declarations are registered.

Is JAXBElement only for roots?

No. xjc also uses it for fields when the element name or nil state carries meaning, for example for substitution groups, choices between elements of the same type, and nillable elements with minOccurs="0".

How does Spring Web Services handle this?

Endpoint methods can take and return JAXBElement<T> directly, and Jaxb2Marshaller marshals the wrapper with the element name it carries. That is common for SOAP payloads generated from WSDL schemas with named types.

7Conclusion

In this answer, we saw that xjc adds @XmlRootElement only for global elements with anonymous complex types, because only then does one class always mean one element. For named types, it generates @XmlElementDecl factory methods in ObjectFactory that return JAXBElement<T>. We marshal by wrapping the value with objectFactory.createOrder(value) or new JAXBElement<>(qname, type, value), unmarshal with unmarshal(source, OrderType.class).getValue(), and use the wrapper's name and nil flag when they carry meaning. Customisations can add root annotations, but JAXBElement is the standard way.

What to say in the interviewAbout 80 seconds aloud

Open with

xjc adds @XmlRootElement only when a global element is declared with an anonymous complex type, because then the generated class and the element are the same thing. When a global element uses a named complex type, that type might be used by several elements, say order and cancelOrder, so xjc cannot know which name an instance should have.

Then, if they want more

It generates the class without a root annotation and adds a method in ObjectFactory, annotated with @XmlElementDecl, that returns a JAXBElement of that type. A JAXBElement is a wrapper with the element's QName, the declared type and the value.

To marshal, I wrap the object, preferably with objectFactory.createOrder, or with new JAXBElement passing the QName, the class and the value; marshalling the bare object fails with a missing @XmlRootElement error. To unmarshal, I call unmarshal with a Source and OrderType.class, which returns a JAXBElement, and take getValue, or JAXBIntrospector.getValue for either form.

I keep the wrapper when its name matters, for example to tell order from cancelOrder, and it also carries nil for nillable elements. Binding customisations like simple mode or plugins can add root annotations, but JAXBElement is the standard, portable way, and I would never edit generated code.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "When does xjc generate classes without @XmlRootElement, and how do you marshal and...": https://scrivio-interview-library.netlify.app/java/jaxb/ad390f6790/