You could use an XmlAdapter
to handle this use case.
GMonthAdapter
package forum13872065;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.datatype.*;
public class GMonthAdapter extends XmlAdapter<String, XMLGregorianCalendar> {
DatatypeFactory dtf;
public GMonthAdapter() {
try {
dtf = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
throw new RuntimeException(e);
}
}
@Override
public XMLGregorianCalendar unmarshal(String v) throws Exception {
return dtf.newXMLGregorianCalendar(v);
}
@Override
public String marshal(XMLGregorianCalendar v) throws Exception {
String string = v.toXMLFormat();
if(string.endsWith("--")) {
return string.substring(0,4);
}
return string;
}
}
Root
The @XmlJavaTypeAdapter
annotation is used to reference the XmlAdapter
.
package forum13872065;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.datatype.XMLGregorianCalendar;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement(name = "Month")
@XmlSchemaType(name = "gMonth")
@XmlJavaTypeAdapter(GMonthAdapter.class)
protected XMLGregorianCalendar month;
}
Demo
Below is some demo code to prove that everything works.
package forum13872065;
import javax.xml.bind.*;
import javax.xml.datatype.DatatypeFactory;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Root root = new Root();
DatatypeFactory dtf = DatatypeFactory.newInstance();
root.month = dtf.newXMLGregorianCalendar("--11");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
Output
Below is the output from running the demo code.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<Month>--11</Month>
</root>