Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 380
ᄂ ᄀ Avatar asked Jun 30 '10 09:06

ᄂ ᄀ


2 Answers

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();
    }

}
like image 89
ᄂ ᄀ Avatar answered Sep 25 '22 06:09

ᄂ ᄀ


EclipseLink MOXy offers a JAXB 2.2 implementation with extensions. One of the extended capabilities is to use XPath to navigate through layers of the XML you don't want in you domain model.

If you look at:

http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted/MOXyExtensions

you will notice that the Customer's name is stored within but that the name is a String attribute of Customer. This is accomplished using:

@XmlPath("personal-info/name/text()")
public String getName() {
    return name;
}

I hope this helps,

Doug

like image 36
Doug Clarke Avatar answered Sep 25 '22 06:09

Doug Clarke