I would like to setup a JAXB-annotated Java class to generate some XML in the following format:
<page refId="0001">
<title>The title of my page</title>
</page>
The "refId" field is optional, so I'd like to use Guava's Optional construct to reference the string in memory. I see Using generic @XmlJavaTypeAdapter to unmarshal wrapped in Guava's Optional, which gives a thorough example if you're using an element (even if that wasn't the original question), but how would you set up the annotations for an XML attribute?
Here's what I have so far:
@XmlRootElement(name="page")
public final class Page {
@XmlAttribute
@XmlJavaTypeAdapter(OptionalAdapter.class)
private Optional<String> refId;
@XmlElement
private String title;
... getters/setters, default constructor, etc.
}
And OptionalAdapter is a simple XmlAdapter:
public class OptionalAdapter<T> extends XmlAdapter<T, Optional<T>> {
@Override
public Optional<T> unmarshal(T v) throws Exception {
return Optional.fromNullable(v);
}
@Override
public T marshal(Optional<T> v) throws Exception {
if (v == null || !v.isPresent()) {
return null;
} else {
return v.get();
}
}
}
When I try to load up a unit test against the above code, it fails instantly during initialization, but if I change the annotation to @XmlElement, the test will run and pass, but obviously sets the refId as a child element instead of an attribute.
Thanks in advance!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…