tags:

views:

50

answers:

1

Hi,

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!

A: 

A very clean way to solve the problem is to create your own converter such as:

public class XMLEventsConverter implements Converter<XMLEvents> {

    private Serializer serializer;

    XMLEventsConverter(Serializer serializer){
        this.serializer = serializer;
    }

    @Override
    public XMLEvents read(InputNode arg0) throws Exception {
        return null;
    }

    @Override
    public void write(OutputNode node, XMLEvents xmlEvents) throws Exception {
        for (XMLEvent event : xmlEvents.events) {
            serializer.write(event, node);
        }
    }

}

And then use a RegistryStrategy and bind the class XMLEvents with the previous converter:

private final Registry registry = new Registry();
private final Serializer serializer = new Persister(new RegistryStrategy(registry));
....
registry.bind(XMLEvents.class, new XMLEventsConverter(serializer));

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!

spderosso