【问题标题】:JAXB: What is the best way to write a method which parses Date of different formats from an XML fileJAXB:编写从 XML 文件中解析不同格式日期的方法的最佳方法是什么
【发布时间】:2020-07-30 02:05:41
【问题描述】:

所以有一种方法可以使用 XmlAdapter 从 XML 中解析日期。 @XmlJavaTypeAdapter(DateAdapter.class)。 但据我所知,这允许解析硬编码格式的日期。有没有办法在运行时将所需的日期格式传递给适配器?或任何其他方式从 XML 解析不同格式的日期。

【问题讨论】:

  • 您可以在字段级别应用@XmlJavaTypeAdapter,因此对不同的字段使用不同的类。还是您的意思是在运行时选择格式来解组相同的映射类?
  • @areus 我希望它只是我想要使用的所有格式的一个类,因为为每种日期格式创建不同的类似乎有点尴尬。
  • 在解组操作期间只能有一个适配器实例。因此,如果同一个 XML 有不同的字段需要不同的格式,那是做不到的。如果在解组期间只有一种格式,它将起作用。

标签: java xml parsing jaxb


【解决方案1】:

通常,当您使用@XmlJavaTypeAdapter 声明XmlAdapter 时,JAXB 会使用空构造函数创建此适配器的实例,以便在编组或解组操作期间使用它。

但是UnmarshallerMarshaller 接口有提供适配器实例的方法。

您可以为您的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(....);

【讨论】:

    猜你喜欢
    • 2015-06-14
    • 2013-08-25
    • 2022-06-23
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多