如何指定JAXB封送xsd:dateTime使用的日期格式? [英] How do you specify the date format used when JAXB marshals xsd:dateTime?
问题描述
当JAXB将日期对象( XMLGregorianCalendar
)编组到xsd:dateTime元素中时如何指定生成的XML的格式?
When JAXB marshals a date object (XMLGregorianCalendar
) into an xsd:dateTime element how can you specify the format of the resulting XML?
例如:
默认数据格式使用毫秒< StartDate> 2012-08-21T13:21:58.000Z< / StartDate>
我需要省略毫秒。 < StartDate> 2012-08-21T13:21:58Z< / StartDate>
如何指定我想要使用的输出格式/日期格式?
我使用 javax.xml.datatype.DatatypeFactory
来创建 XMLGregorianCalendar
对象。
How can I specify the output form/date format that I want it to use?
I'm using javax.xml.datatype.DatatypeFactory
to create the XMLGregorianCalendar
object.
XMLGregorianCalendar xmlCal = datatypeFactory.newXMLGregorianCalendar(cal);
推荐答案
您可以使用 XmlAdapter
来定制日期类型是如何写入XML的。
You can use an XmlAdapter
to customize how a date type is written to XML.
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class DateAdapter extends XmlAdapter<String, Date> {
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public String marshal(Date v) throws Exception {
synchronized (dateFormat) {
return dateFormat.format(v);
}
}
@Override
public Date unmarshal(String v) throws Exception {
synchronized (dateFormat) {
return dateFormat.parse(v);
}
}
}
然后你使用 @XmlJavaTypeAdapter
注释来指定特定字段/属性应使用 XmlAdapter
。
Then you use the @XmlJavaTypeAdapter
annotation to specify that the XmlAdapter
should be used for a specific field/property.
@XmlElement(name = "timestamp", required = true)
@XmlJavaTypeAdapter(DateAdapter.class)
protected Date timestamp;
使用xjb绑定文件:
<jxb:javaType name="java.time.ZonedDateTime"
xmlType="xs:dateTime"
parseMethod="my.package.DateAdapter.parseDateTime"
printMethod="my.package.DateAdapter.formatDateTime" />
将产生上述注释。
这篇关于如何指定JAXB封送xsd:dateTime使用的日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!