如何指定 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>
For example:
The default data format uses milliseconds <StartDate>2012-08-21T13:21:58.000Z</StartDate>
I need to omit the milliseconds. <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.
package com.example;
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 绑定文件:
Using a xjb binding file:
<xjc:javaType name="java.util.Date" xmlType="xs:dateTime"
adapter="com.example.DateAdapter"/>
将产生上述注释.
(通过最终添加 xjc
命名空间:xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
)
will produce the above mentioned annotation.
(By eventually adding the xjc
namespace: xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
)
这篇关于如何指定 JAXB 编组 xsd:dateTime 时使用的日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!