如何解决为多种 xsd 类型指定一个适配器
我正在尝试将不同的格式映射到 3 个 xsd 类型,xs:dateTime、xs:date 和 xs:time。我在我的项目中做了一些代码生成,并且没有绑定文件,但我有一个包信息。
@javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters({
@javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter(value = com.codegen.pojo.lib.adapters.XmlDateTimeFormatter.class,type = com.codegen.pojo.lib.types.IXmlDateTime.class)
})
@javax.xml.bind.annotation.XmlSchemaTypes({
@javax.xml.bind.annotation.XmlSchemaType(name = "dateTime",type = com.codegen.pojo.lib.types.XmlDateTime.class),@javax.xml.bind.annotation.XmlSchemaType(name = "date",type = com.codegen.pojo.lib.types.XmlDate.class),@javax.xml.bind.annotation.XmlSchemaType(name = "time",type = com.codegen.pojo.lib.types.XmlTime.class)
})
@com.codegen.pojo.lib.annotations.XMLDateTimeFormat(format = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXX")
@com.codegen.pojo.lib.annotations.XMLDateFormat(format = "yyyy-MM-dd'T'")
@com.codegen.pojo.lib.annotations.XMLTimeFormat(format = "'T'HH:mm:ss.SSSXXXX")
package my_pkg;
XmlSchemaType 注释中提到的所有 3 个 Xml(Date/Time) 类都实现了 IXmlDateTime 接口。 适配器:
public class XmlDateTimeFormatter extends XmlAdapter<String,IXmlDateTime> {
private final DateTimeFormatter dateTimeFormat;
private final DateTimeFormatter dateFormat;
private final DateTimeFormatter timeFormat;
public XmlDateTimeFormatter(String dateTimeFormatPattern,String dateFormatPattern,String timeFormatPattern) {
dateTimeFormat = dateTimeFormatPattern == null ? null : DateTimeFormatter.ofPattern(dateTimeFormatPattern);
dateFormat = dateFormatPattern == null ? null : DateTimeFormatter.ofPattern(dateFormatPattern);
timeFormat = timeFormatPattern == null ? null : DateTimeFormatter.ofPattern(timeFormatPattern);
}
@Override
public String marshal(IXmlDateTime dateTime) throws Exception {
if (dateTime instanceof XmlDateTime) {
return dateTimeFormat.format(dateTime.getCalendar().toGregorianCalendar().tozoneddatetime());
} else if (dateTime instanceof XmlDate) {
return dateFormat.format(dateTime.getCalendar().toGregorianCalendar().tozoneddatetime());
} else if (dateTime instanceof XmlTime) {
return timeFormat.format(dateTime.getCalendar().toGregorianCalendar().tozoneddatetime());
}
return null;
}
@Override
public IXmlDateTime unmarshal(String dateTime) throws Exception {
XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(dateTime);
QName xmlFormat = calendar.getXMLSchemaType();
if (xmlFormat.equals(DatatypeConstants.DATETIME)) {
return new XmlDateTime(calendar);
} else if (xmlFormat.equals(DatatypeConstants.DATE)) {
return new XmlDate(calendar);
} else if (xmlFormat.equals(DatatypeConstants.TIME)) {
return new XmlTime(calendar);
}
return null;
}
适配器被添加到从 JAXBContext 创建的 Marshaller/Unmarshaller。不幸的是,marshal 或 unmarshal 都没有被调用。关于如何解决这个问题的任何想法?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。