-1

I need to save user data between sessions. So I decided to using binary serialization and start saving data in xml. After some research I found several APIs, namely JAXB and xStream.

I looked through samples of xStream and I like it. It is very simple. In two words: you give an object and receive .xml representation of this object. Read an xml and receive object back.

Then I read about JAXB - it is very strong, functional. But all examples I found are about creating of xml schema, generating java classes basing on this schema and so on. At the moment it looks a little bit time consuming for me to describe my classes in .xsd. I hope it is one of many sides of JAXB usage. But what I saw, feared me a little.

Are there any other APIs that suit my task. Or what are pros and cons of JAXB and xStream then?

4

2 回答 2

3

I would start with JAXB as it is built-in and easy to use. You do not need to start with an XSD. Just add some annotations to your classes.

@XmlRootElement(name="doc")
public class Document {
   @XmlElement
   protected Foo foo;
   // ...
}

Serialization:

Document doc = new Document();

JAXBContext jc = JAXBContext.newInstance(Document.class);
Marshaller m = jc.createMarshaller();
m.marshal(doc, System.out);

Deserialization:

JAXBContext jc = JAXBContext.newInstance(Document.class);
Unmarshaller u = jc.createUnmarshaller();
Document doc = u.unmarshal(System.in);

Replace System.out and System.in by your actual streams and you are ready to go.

There is a short tutorial regarding JAXB Annotations in the JAXB tutorial:

于 2013-02-15T11:24:17.067 回答
0

When JAXB is a bit too much of a powerhouse, and a simpler solution could be better, I generally try Castor.

The good part is, you can use the simple introspection mode, quick and easy, and if you ever feel like you need more control over your generated XML, add a descriptor or mapping, but both are optional.

于 2013-02-15T11:06:51.417 回答