JAXB:将单独的日期和时间元素映射到一个属性
我正在使用如下所示的 XML 结构:
<ROOT>
<ELEM_A>
<A_DATE>20100825</A_DATE>
<A_TIME>141500</A_TIME>
<!-- other elements, maybe also other or date/time combinations -->
<STRING>ABC</STRING>
<ELEM_A>
<ELEM_B>
<B_DATE>20100825</B_DATE>
<B_TIME>153000</B_TIME>
<NUM>123</NUM>
<C_DATE>20100825</C_DATE>
<C_TIME>154500</C_TIME>
</ELEM_B>
</ROOT>
我想将日期和时间映射到 bean 中的单个 Date
或 Calendar
属性。使用 jaxb 注释可以吗? javax.xml.bind.annotation.adapters.XmlAdapter 类看起来可能能够做到这一点,但我必须承认我并不完全理解它的 javadoc。
解决方法是为日期和时间字符串创建额外的设置器,以在 Calendar
属性中设置相应的值,如下所示:
private Calendar calendar;
public void setDate(String date) {
if (calendar == null) {
calendar = new GregorianCalendar();
}
calendar.set(YEAR, Integer.parseIn(date.substring(0, 4)));
calendar.set(MONTH, Integer.parseIn(date.substring(4, 6))-1);
calendar.set(DAY_OF_MONTH, Integer.parseIn(date.substring(6, 8)));
}
// Similar code for setTime
问题(除了附加代码之外)是我不能总是保证日期设置在时间值之前,但我想不出一个具体的例子,这可能会给出磨损的结果。
任何基于注释的解决方案的示例或上述代码的改进/反示例都值得赞赏。
编辑:我采用了Blaise Doughan给出的第二个答案,但修改了他的 DateAttributeTransformer更加灵活,并且不期望字段名称包含字符串“DATE”。字段名称取自字段上的 XmlWriterTransformer 注释:
@Override
public Object buildAttributeValue(Record record, Object instance, Session session) {
try {
String dateString = null;
String timeString = null;
String dateFieldName = null;
String timeFieldName = null;
// TODO: Proper Exception handling
try {
XmlWriteTransformers wts = instance.getClass().getDeclaredField(mapping.getAttributeName()).getAnnotation(XmlWriteTransformers.class);
for (XmlWriteTransformer wt : wts.value()) {
String fieldName = wt.xpath();
if (wt.transformerClass() == DateFieldTransformer.class) {
dateFieldName = fieldName;
} else {
timeFieldName = fieldName;
}
}
} catch (NoSuchFieldException ex) {
throw new RuntimeException(ex);
} catch (SecurityException ex) {
throw new RuntimeException(ex);
}
for(DatabaseField field : mapping.getFields()) {
XMLField xfield = (XMLField)field;
if(xfield.getXPath().equals(dateFieldName)) {
dateString = (String) record.get(field);
} else {
timeString = (String) record.get(field);
}
}
return yyyyMMddHHmmss.parseObject(dateString + timeString);
} catch(ParseException e) {
throw new RuntimeException(e);
}
}
I'm working with a XML structure that looks like this:
<ROOT>
<ELEM_A>
<A_DATE>20100825</A_DATE>
<A_TIME>141500</A_TIME>
<!-- other elements, maybe also other or date/time combinations -->
<STRING>ABC</STRING>
<ELEM_A>
<ELEM_B>
<B_DATE>20100825</B_DATE>
<B_TIME>153000</B_TIME>
<NUM>123</NUM>
<C_DATE>20100825</C_DATE>
<C_TIME>154500</C_TIME>
</ELEM_B>
</ROOT>
And I want to map date and time to a single Date
or Calendar
property in my bean. Is this possible using jaxb annotations? The class javax.xml.bind.annotation.adapters.XmlAdapter
looks like it might be able to do this, but I have to admit I don't fully understand its javadoc.
A workaround would be to create additional setters for the date and time strings that set the corresponding values in a Calendar
property like this:
private Calendar calendar;
public void setDate(String date) {
if (calendar == null) {
calendar = new GregorianCalendar();
}
calendar.set(YEAR, Integer.parseIn(date.substring(0, 4)));
calendar.set(MONTH, Integer.parseIn(date.substring(4, 6))-1);
calendar.set(DAY_OF_MONTH, Integer.parseIn(date.substring(6, 8)));
}
// Similar code for setTime
The problem (apart from the additional code) is that I can't always guarantee that the date is set before the time value, but I can't think of a specific example where this might give worng results.
Any examples for an annotation based solution or improvements / counter examples for the code above are appreciated.
Edit: I went with the second answer given by Blaise Doughan, but modified his DateAttributeTransformer to be more flexible and not expect the field name to contain the string "DATE". The field names are taken from the XmlWriterTransformer annotations on the field:
@Override
public Object buildAttributeValue(Record record, Object instance, Session session) {
try {
String dateString = null;
String timeString = null;
String dateFieldName = null;
String timeFieldName = null;
// TODO: Proper Exception handling
try {
XmlWriteTransformers wts = instance.getClass().getDeclaredField(mapping.getAttributeName()).getAnnotation(XmlWriteTransformers.class);
for (XmlWriteTransformer wt : wts.value()) {
String fieldName = wt.xpath();
if (wt.transformerClass() == DateFieldTransformer.class) {
dateFieldName = fieldName;
} else {
timeFieldName = fieldName;
}
}
} catch (NoSuchFieldException ex) {
throw new RuntimeException(ex);
} catch (SecurityException ex) {
throw new RuntimeException(ex);
}
for(DatabaseField field : mapping.getFields()) {
XMLField xfield = (XMLField)field;
if(xfield.getXPath().equals(dateFieldName)) {
dateString = (String) record.get(field);
} else {
timeString = (String) record.get(field);
}
}
return yyyyMMddHHmmss.parseObject(dateString + timeString);
} catch(ParseException e) {
throw new RuntimeException(e);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
XmlAdapter 是正确的方法:
具有 Date 属性的类
XmlAdapter 的实现
适配的 Date 对象
示例程序
XML 文档
有关详细信息,请参阅:
XmlAdapter is the right approach:
Class with Date property
The implementation of XmlAdapter
The adapted Date object
Sample program
XML Document
For more information see:
您可以使用 MOXy JAXB 实现(我是技术主管),而不是使用 JAXB RI (Metro)。它有一些扩展,可以使映射此场景变得相当容易。
jaxb.properties
要使用 MOXy 作为 JAXB 实现,您需要在与模型类相同的包中添加一个名为 jaxb.properties 的文件,其中包含以下条目:
Root
ElemA
我们可以利用@XmlTransformation。它在概念上与 XmlAdapter 类似,但更容易在映射之间共享。
ElemB
DateAttributeTransformer
属性转换器负责解组 Date 对象。
DateFieldTransformer
字段转换器负责编组 Date 对象。
TimeFieldTransformer
示例程序
XML文档
上面所示的代码需要当前正在开发的EclipseLink 2.2。每晚构建可在此处获得:
当前发布的 EclipseLink 2.1 版本支持上述内容,但配置略有不同。如果您有兴趣探索此选项,我们可以讨论适当的设置。
Instead of using the JAXB RI (Metro), you could use the MOXy JAXB implementation (I'm the tech lead). It has some extensions that will make mapping this scenario fairly easy.
jaxb.properties
To use MOXy as your JAXB implementation you need to add a file named jaxb.properties in the same package as your model classes with the following entry:
Root
ElemA
We can leverate @XmlTransformation. It is similar in concept to XmlAdapter, but easier to share among mappings.
ElemB
DateAttributeTransformer
The attribute transformer is responsible for unmarshalling the Date object.
DateFieldTransformer
The field transformers are responsible for marshalling the Date object.
TimeFieldTransformer
Sample Program
XML Document
The code as shown above requires EclipseLink 2.2 currently under development. A nightly builds are available here:
The current released version of EclipseLink 2.1 supports the above, but with a slightly different configuration. We can discuss the appropriate setup if you are interested in exploring this option.