SimpleXML 仅支持某些 :DateFormat
- 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);