2009-11-15

Converting from JAXB to Simple XML

Since JAXB doesn't work on Google App Engine but Simple XML does I have been converting my application. I'm using XML in quite a loose way; I have only annotated my classes for the elements and attributes which I want to extract from the larger XML document. JAXB is more forgiving when used in this way, however with a few extra parameters the same can be achieved with Simple XML. Here is a table of a few things I had to convert:

Description JAXB Simple XML
The RSS element that is being deserialized has a version attribute on it but I do not wish to model this in the Java class. I only want to deserialize the channel element
@XmlRootElement(name="rss")
static class Rss {    
 @XmlElement(name="channel")
 Channel channel;
}

@Root(name="rss", strict=false)
static class Rss {    
 @Element(name="channel")
 Channel channel;
}
The channel element contains a list of item elements without any wrapper element enclosing the whole list.
static class Channel {
 @XmlElement(name="item")
 List<Item> items;
}

@Root(strict=false)
static class Channel {
 @ElementList(entry="item", inline=true)
 List<Item> items;
}
A List with a wrapper element.
@XmlElementWrapper(name="customfieldvalues")
@XmlElement(name="customfieldvalue")
List<String> customfieldvalues;

@ElementList(entry="customfieldvalue", 
  required=false)
List<String> customfieldvalues;
Deserialize
JAXBContext jaxbContext = 
  JAXBContext.newInstance(Rss.class);
Unmarshaller unmarshaller = 
  jaxbContext.createUnmarshaller();
Rss rss = 
  (Rss) unmarshaller.unmarshal(in);

Serializer serializer = new Persister();
Rss rss = 
  serializer.read(Rss.class, in);

2 comments:

Unknown said...
This comment has been removed by the author.
Unknown said...

hi! I'm trying to convert a JAXB code to Simple. I have to deal with JAXBElement. I don't really know what its equivalent is in Simple.Can you help please?
thx