Handling nested elements in JAXB



I am wondering if it is possible to have JAXB not to create Java object for XML elements that serve as wrappers. For example, for XML of the following structure

<root>
    <wrapper>
        <entity/>
    </wrapper>
</root>

I do not want an object for <wrapper> to be created at all. So for a class like

class Root {
    private Entity entity;
}

the <entity> element should be unmarshalled directly into the entity field.

Is it possible to achieve with JAXB?

Answer

Although it requires extra coding, the desired unmarshalling is accomplished in the following way using a transient wrapper object:

@XmlRootElement(name = "root")
public class Root {

    private Entity entity;

    static class Entity {

    }

    static class EntityWrapper {
        @XmlElement(name = "entity")
        private Entity entity;

        public Entity getEntity() {
            return entity;
        }
    }

    @XmlElement(name = "wrapper")
    private void setEntity(EntityWrapper entityWrapper) {
        entity = entityWrapper.getEntity();
    }

}


Source: stackoverflow