JAXB:编写从 XML 文件解析不同格式日期的方法的最佳方法是什么
JAXB: What is the best way to write a method which parses Date of different formats from an XML file
所以有一种方法可以使用 XmlAdapter 从 XML 解析日期。
@XmlJavaTypeAdapter(DateAdapter.class)
。
但据我所知,这允许解析硬编码格式的日期。有没有办法在运行时将所需的日期格式传递给适配器?或从 XML.
解析不同格式的日期的任何其他方式
通常当您使用 @XmlJavaTypeAdapter
声明 XmlAdapter
时,JAXB 使用空构造函数创建此适配器的实例以在编组或解组操作期间使用它。
但是 Unmarshaller
和 Marshaller
接口有一个提供适配器实例的方法。
您可以为您的 DateAdapter
提供一个备用构造函数,其中包含您要使用的格式的参数,并声明一个 DEFAULT_FORMAT。像这样:
private String format;
public DateAdapter() {
this(DEFAULT_FORMAT);
}
public DateAdapter(String format) {
this.format = format;
}
当你需要解组时:
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setAdapter(DateAdapter.class, new DateAdapter(someFormat));
Object o1 = unmarshaller.unmarshal(....);
unmarshaller.setAdapter(DateAdapter.class, new DateAdapter(otherFormat));
Object o2 = unmarshaller.unmarshal(....);
所以有一种方法可以使用 XmlAdapter 从 XML 解析日期。
@XmlJavaTypeAdapter(DateAdapter.class)
。
但据我所知,这允许解析硬编码格式的日期。有没有办法在运行时将所需的日期格式传递给适配器?或从 XML.
通常当您使用 @XmlJavaTypeAdapter
声明 XmlAdapter
时,JAXB 使用空构造函数创建此适配器的实例以在编组或解组操作期间使用它。
但是 Unmarshaller
和 Marshaller
接口有一个提供适配器实例的方法。
您可以为您的 DateAdapter
提供一个备用构造函数,其中包含您要使用的格式的参数,并声明一个 DEFAULT_FORMAT。像这样:
private String format;
public DateAdapter() {
this(DEFAULT_FORMAT);
}
public DateAdapter(String format) {
this.format = format;
}
当你需要解组时:
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setAdapter(DateAdapter.class, new DateAdapter(someFormat));
Object o1 = unmarshaller.unmarshal(....);
unmarshaller.setAdapter(DateAdapter.class, new DateAdapter(otherFormat));
Object o2 = unmarshaller.unmarshal(....);