[lazyweb] Microformat databinding
December 11th, 2007Has anyone ever written a java library which takes a pojo and turns it into a microformat? I.e. I have POJO Person with name, address, phone number fields and it gets changed into:
<div class="person">
<span class="name">Dan Diephouse<span>
<span class="address">1 Main St<span>
<span class="phone">+15555551212<span>
<div>
This is probably evil, but you must realize that I’ve written a helluva a lot of Object->WSDL crap over the years so I really don’t feel my evil quotient will be affected by this too much.
December 11th, 2007 at 3:11 pm
Hey Dan, won’t JAXB, JPOX or the like with annotations on the POJO address this?
December 11th, 2007 at 4:28 pm
Not AFAIK. That would output something like:
<person>
<name>…</name>
</person>
The point here is to get out XHTML microcontent as opposed to just straight up XML.
December 11th, 2007 at 6:59 pm
No, I haven’t. But this looks interesting. Because it results in a closer shape to JSON than the typical way people would serialize (your example above). Specifically, if you serialize this way, you could standardize the elements you used for ‘objects’ (div), attributes (span), arrays (ol), etc.
December 12th, 2007 at 4:32 am
import java.util.*;
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
public class MicroformatViaJaxb
{
public static void main( String[] args ) throws JAXBException
{
Microformat mf = new Microformat();
mf.elements.add( new Element( “name”, “Christian Ullenboom” ) );
mf.elements.add( new Element( “address”, “1 Main St” ) );
mf.elements.add( new Element( “phone”, “+15555551212″ ) );
//
JAXBContext context = JAXBContext.newInstance( Microformat.class );
Marshaller m = context.createMarshaller();
m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
m.marshal( mf, System.out );
}
}
@XmlRootElement( name = “div” )
class Microformat
{
@XmlAttribute( name = “class” )
public String key = “person”;
@XmlElement( name = “span” )
public List elements = new ArrayList();
}
class Element
{
@XmlAttribute( name = “class” )
public String key;
@XmlValue
public String value;
public Element()
{
}
public Element( String key, String value )
{
this.key = key;
this.value = value;
}
}
December 12th, 2007 at 4:35 am
My solution is not using a Person-POJO, but I think a POJO should not be JAXB-annotated to write a microformat. So mapping to an intermediate is IMO a good design decision.
December 12th, 2007 at 11:31 am
Try XStream or a template engine (Freemarker, Velocity)
December 16th, 2007 at 12:55 pm
Christian: yeah that is definitely an option.
Peter: I don’t think XStream will do that… Velocity is definitely an option, but still more work than I want it to be.