Reputation: 31
I am converting from SAX parser to JAXB - can't figure out how to unmarshall multiple tag/attribute values into single (compassable) Java POJO.
I have xml file like this:
<item validFrom="1950" validUntil="1980">
<description>some text</description>
</item>
the "validFrom" and "validUntil" values should be composed into a valid "MutableRange" POJO (see definition below).
the Java Item definition that I need to unmarshall it to is:
@XmlRootElement
@XmlAccessorType(XmlAcccessType.FIELD)
public class Item {
// ??? need help mapping this to be composed from "validFrom", "validUntil" attributes
private MutableRange validRange;
@XmlElement
private String description;
}
// assume all other boilerplate code exists
public class MutableRange {
private int lowerBound;
private int upperBound;
}
I have tried using an adapter but its not capturing both: "from" and "until" values together for me to create MutableRange instance. I tried using @XmlMixed
with no success.
What is JAXB prescribed way to accomplish this?
Once this is resolved, I will extend MutableRange
with (XmlAdapter
) to serve as a wrapper to create guava's immutable Range object, mapping it to validRange
with @XmlJavaTypeAdapter(MutableRange.class)
Upvotes: 2
Views: 576
Reputation: 1303
I would use something as simple as:
public interface MutableRange() {
public int getLowerBound();
public int getUpperBound();
public void setLowerBound(int lowerBound);
public void setUpperBound(int upperBound);
}
@XmlRootElement(name = "item")
@XmlAccessorType(XmlAccessType.NONE)
public class Item {
@XmlAttribute(name = "validFrom")
private int validFrom;
@XmlAttribute(name = "validUntil")
private int validUntil;
@XmlElement(name = "description")
private String description;
public MutableRange getValidRange() {
return new MutableRange() {
public int getLowerBound() { return validFrom; }
public int getUpperBound() { return validUntil; }
public void setLowerBound(int lowerBound) { validFrom = lowerBound; }
public void setUpperBound(int upperBound) { validUntil = upperBound; }
}
}
public String getDescription() {
return description;
}
}
Upvotes: 0
Reputation: 149047
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
You can use MOXy's @XmlPath
extension to map this use case:
@XmlRootElement
@XmlAccessorType(XmlAcccessType.FIELD)
public class Item {
@org.eclipse.persistence.oxm.annotations.XmlPath(".")
private MutableRange validRange;
@XmlElement
private String description;
}
For More Information
Upvotes: 1