Franz Kafka
Franz Kafka

Reputation: 10851

JAXB convert multiple attributes to one type while unmarshalling

Image I have an element like this <someElement a="" b="" number="1" scale="meters"><child/></someElement>

scale and number always appear together but they are not defined in one exclusive element.

When unmarshalling the someElement element to a SomeElement java instance I want a single member in the SomeElement class to represent number and scale.

At the moment both number and scale are attributes and then the afterUnmarshall() method is used for calculating one number.

Is there a way to do this without having the two member fields size and scale? Maybe with a XmlAdapter? How would I use this in this case?

Upvotes: 1

Views: 2197

Answers (2)

bdoughan
bdoughan

Reputation: 149057

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.

MOXy offers the @XmlTransformation extension that allows you to represent a Java field/property as several XML nodes.

For More Information

UPDATE

Alternatively you could use an XmlAdapter for this use case. The adapter will we responsible for converting the single type representing number and scale (represented as FOO below) to a type with separate properties for number and scale. You will still need to use the MOXy implementation to leverage the @XmlPath extension:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class SomeElement {

    @XmlAttribute
    private String a;

    @XmlAttribute
    private String b;

    @XmlJavaTypeAdapter(NumberAndScaleAdapter.class)
    @XmlPath(".")
    private FOO numberAndScale;

    private Child child;

}

For More Information

Upvotes: 1

G_H
G_H

Reputation: 12019

The answers for this question seem to correspond with what you're trying to do. Or at least some reverse of it. So you can either create a custom type that un/marshals using an XmlAdapter, or you can be mischievous with your getter/setter logic.

Upvotes: 1

Related Questions