我应该如何在Java中用简单的xml映射抽象类?
我想使用简单的 xml 框架实现以下 xml (http://simple.sourceforge.net/) :
<events>
<course-added date="01/01/2010">
...
</course-added>
<course-removed date="01/02/2010">
....
</course-removed>
<student-enrolled date="01/02/2010">
...
</student-enrolled>
</events>
我有以下内容(但它没有实现所需的 xml):
@Root(name="events")
class XMLEvents {
@ElementList(inline=true)
ArrayList<XMLEvent> events = Lists.newArrayList();
...
}
abstract class XMLEvent {
@Attribute(name="date")
String dateOfEventFormatted;
...
}
以及具有不同信息的不同类型的 XMLNode(但都是不同类型的事件)
@Root(name="course-added")
class XMLCourseAdded extends XMLEvent{
@Element(name="course")
XMLCourseLongFormat course;
....
}
@Root(name="course-removed")
class XMLCourseRemoved extends XMLEvent {
@Element(name="course-id")
String courseId;
...
}
我应该如何进行映射或者我应该更改什么才能成为能够实现de想要的xml吗?
谢谢!
I want to achieve the following xml using simple xml framework (http://simple.sourceforge.net/):
<events>
<course-added date="01/01/2010">
...
</course-added>
<course-removed date="01/02/2010">
....
</course-removed>
<student-enrolled date="01/02/2010">
...
</student-enrolled>
</events>
I have the following (but it doesn't achieve the desired xml):
@Root(name="events")
class XMLEvents {
@ElementList(inline=true)
ArrayList<XMLEvent> events = Lists.newArrayList();
...
}
abstract class XMLEvent {
@Attribute(name="date")
String dateOfEventFormatted;
...
}
And different type of XMLNodes that have different information (but are all different types of events)
@Root(name="course-added")
class XMLCourseAdded extends XMLEvent{
@Element(name="course")
XMLCourseLongFormat course;
....
}
@Root(name="course-removed")
class XMLCourseRemoved extends XMLEvent {
@Element(name="course-id")
String courseId;
...
}
How should I do the mapping or what should I change in order to be able to achieve de desired xml?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决该问题的一种非常干净的方法是创建您自己的转换器,例如:
然后使用RegistryStrategy 并将类XMLEvents 与先前的转换器绑定:
通过这种方式,获得的xml 就是所需的。请注意,XMLEventsConverter 上的 read 方法只是
返回 null
,如果您需要从 xml 文件重建对象,您应该正确实现它。问候!
A very clean way to solve the problem is to create your own converter such as:
And then use a RegistryStrategy and bind the class XMLEvents with the previous converter:
In this way the xml obtained is the one desired. Note that the read method on the XMLEventsConverter just
return null
, in case you need to rebuild the object from the xml file you should properly implement it.Regards!
看起来您现在可以使用 @ElementListUnion 功能来执行此操作
这将打印出:
Looks like you can do this now using the @ElementListUnion functionality
This will print out: