SimpleXML 只支持一些DateFormat
's:
- yyyy-MM-dd HH:mm:ss.S z
- yyyy-MM-dd HH:mm:ss z
- yyyy-MM-dd z
- yyyy-MM-dd
(有关每个字符的含义,请参见SimpleDateFormat API Doc (Java SE 7))
但是,可以编写Transform
处理其他格式的自定义:
转换
public class DateFormatTransformer implements Transform<Date>
{
private DateFormat dateFormat;
public DateFormatTransformer(DateFormat dateFormat)
{
this.dateFormat = dateFormat;
}
@Override
public Date read(String value) throws Exception
{
return dateFormat.parse(value);
}
@Override
public String write(Date value) throws Exception
{
return dateFormat.format(value);
}
}
对应注解
@Attribute(name="regDate", required=true) /* 1 */
private Date registerDate;
注1: required=true
可选
如何使用它
// Maybe you have to correct this or use another / no Locale
DateFormat format = new SimpleDateFormat("EE MMM dd HH:mm:ss z YYYY", Locale.US);
RegistryMatcher m = new RegistryMatcher();
m.bind(Date.class, new DateFormatTransformer(format));
Serializer ser = new Persister(m);
Example e = ser.read(Example.class, xml);