[jdom-interest] converting Elements to objects

Jason Winnebeck gillius at gillius.org
Thu Feb 17 14:27:14 PST 2005

Anton Stoyanov wrote:

 > Jason, you say makeCustomer would read out the fields..... can I make
 > this generic - so that it's not makeCustomer but "makeObject(Element
 > e)" which will just take in an element and automatically recognize if
 > it's a customer or saleitem or whatever object and make old the
 > children into strings, say, in that object.

Yes, as I said in my first e-mail (without giving explicit code), I did say 
you could do that, but it wouldn't be any easier.  Of course, you can 
implement a method makeObject such that:

public static Object makeObject( Element e ) {
   if ( e.getName() == "customer" )
     return makeCustomer( e );
   else if ( e.getName() == "saleitem" )
     return makeSaleItem( e );

You could also implement the following with a Map< String, XMLObjectFactory 
 > where you make XMLObjectFactory implementations for each type of object. 
  XMLObjectFactory would be an interface with method "Object makeObject( 
Element e)" then you would construct the map thusly:

map.put( "customer", new XMLCustomerFactory() );

and use it thusly:

return map.get( "customer" ).makeObject( e ); //error checking left out

If you are thinking you are going to get automatic code that somehow 
automagically relates XML tags to name fields and writes code for you, you 
won't find it (at least not in the form you are thinking of).

Jason Winnebeck

More information about the jdom-interest mailing list