对象到XML,向后和向前兼容性 [英] Object to XML, backward and forward compatibility

查看:112
本文介绍了对象到XML,向后和向前兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个应用程序中工作,我们需要以XML格式保存对象,并在需要时稍后加载它们。为此,我使用JAXB来编组和解组XML到Java类。

I am working in an application where we need to save objects in XML format, and load them later once required. For this I have used JAXB to marshall and unmarshall XMLs back to Java classes.

我的问题是我必须在某个时候更改Java模型(通过添加,重命名或删除因此,我将拥有不兼容的已保存的XML,这些XML无法绑定到新的类表单。

My problem is that the I have to change Java models sometime (by adding, renaming or deleting attributes), as a result, I will have incompatible saved XMLs which can’t be bound back to the new class form.

要解决此问题,每次我必须做一个更改我把一个新包下的所有类的副本(以其版本命名)并应用所请求的更改。在保存XML时,我保存了它的版本,以便我可以决定JAXB应该扫描哪个包来解组这个XML。

To solve this, every time I have to do a change I take a copy of all the classes under a new package (named after its version) and apply the requested changes. And when saving an XML I save its version so that I can decide which package should be scanned by JAXB to unmarshall this XML.

我的问题是,还有其他办法使用JAXB实现向后和向前兼容性?如果没有,是否有其他技术可以支持这个?

My question is, Is there any other way to implement backward and forward compatibility using JAXB? If not is there any other technology that can support this?

推荐答案

注意:我是会员JAXB 2( JSR-222 )专家组和主席 EclipseLink JAXB(MOXy)

Note: I am a member of the JAXB 2 (JSR-222) expert group and lead EclipseLink JAXB (MOXy).

为此用例我更喜欢在可能的情况下使用单个模型。这将要求您为对象模型提供多个映射。 JAXB规范没有提供这样做的方法,但可以使用MOXy的外化元数据扩展来完成:

For this use case I prefer to use a single model when possible. This will require that you have multiple mappings for your object model. The JAXB spec does not provide a means to do this, but it can be done using MOXy's externalized metadata extension:

  • http://bdoughan.blogspot.com/2010/12/extending-jaxb-representing-annotations.html

元数据可用于补充注释,或用于替换注释。因此,我建议使用注释映射基本模式,并使用XML格式修改每个模式版本的元数据。

The metadata can be used to supplement the annotations, or used to replace them. So I would recommend mapping your base schema with annotations and using the XML format to modify the metadata per version of the schema.


我的问题是我必须在某个时候更改Java模型
(通过
添加,重命名或删除
属性),因此,我将拥有
无法比较的保存XML,这些不可能是
绑定回新的类表单。

My problem is that the I have to change Java models sometime (by adding, renaming or deleting attributes) , as a result, I will have incompatable saved XMLs which can’t be bound back to the new class form.

删除Java属性(字段/属性)会使事情变得困难,因为会有什么都不是旧的XML映射到。相反,您可以将它们保留在模型中,并在XML元数据文件中将它们标记为@XmlTransient。

Deleting a Java attribute (field/property) makes things difficult since there will be nothing for the old XML to map to. Instead you can leave them in your model, and mark them "@XmlTransient" in the XML metadata files.

这篇关于对象到XML,向后和向前兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆