[jdom-interest] converting Elements to objects

Jason Winnebeck gillius at gillius.org
Thu Feb 17 11:44:36 PST 2005


Anton Stoyanov wrote:
> with JDOM I can get a java.util.List of elements, but how can I
> transform them into customer objects ?

As far as I know, there is not a JDOM method or another automatic method to 
do this.

The way I resolve this is by making a constructor for Customer that takes an 
Element pointing to a customer tag, then reads the children of that tag.

Element e = parent.getChild( "customer" );
Customer c = new Customer( e );

If you want to separate the JDOM/XML parsing away from the design of the 
Customer class (there are various reasons you may object to putting JDOM 
code into the Customer class, espically if you did not write the Customer 
class), you could use a sort of factory.

If your XML is pretty structured and you aren't sure what you are going to 
get out of it you could use a generic factory that returned an object 
implementing an interface, and the specific type is dependent on the tag 
passed in.  Or, if you do know what you are getting, then you could do 
something like:

Element e = parent.getChild( "customer" );
Customer c = XMLObjectFactory.makeCustomer( e );

makeCustomer would presumably read out the fields and call a verbose form of 
constructor for Customer to construct an appropriate new Customer object.

Jason Winnebeck


More information about the jdom-interest mailing list