commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Craig R. McClanahan" <>
Subject Re: [Digester] Attribute Mapping
Date Tue, 25 Feb 2003 21:44:16 GMT

On Tue, 25 Feb 2003, Venkatarman, Rajagopal wrote:

> Date: Tue, 25 Feb 2003 14:16:49 -0500
> From: "Venkatarman, Rajagopal" <>
> Reply-To: Jakarta Commons Users List <>
> To: "''" <>
> Subject: [Digester] Attribute Mapping
> Im trying to use the Digester to map attribute key-value to a bean property.
> This is the format of my XML
> <Employee Name="Raj">

If you make a slight tweak to this and make it:

  <Employee name="Raj"/>

instead, then Digester has a pretty easy way to deal with stuff like this.
Consider that you have a JavaBean called EmployeeBean that has the usual
property getter and setter methods:

  public class EmployeeBean {
    public String getName();
    public void setName(String name);

Now, let's say you want to create an ArrayList of all the employees in
your XML document.  One way to do that would be:

  Digester digester = new Digester();
  List list = new ArrayList();
                      "add", "java.lang.Object");
  InputStream stream = ...; // InputStream for your XML document

The three rules, in order, do this for each <Employee> element
* Create a new instance of EmployeeBean and push it on Digester's stack
* Call all the property setters that have property names matching
  the attributes of this element (so you can populate as many
  properties as you want with just this one rule)
* Pass the top object on the stack (the EmployeeBean you just
  created and populated) to the "add" method of the next-to-top
  object on the stack (the List we pushed at the beginning)
* Pop the EmployeeBean instance off the stack now that we're
  done with it.

The key ease-of-use feature is that all the property names are matched up
dynamically -- but only if your attributes follow the JavaBeans convention
for the property names themselves (start with a lower case letter).  If
you cannot do this, you're going to be stuck either with your XSLT
transformation, or using nested elements the way you did it, or with
creating a custom Rule implementation that can do whatever is needed.

There's lots more examples of this kind of thing in the Digester javadocs
-- especially the Package Description for the org.apache.commons.digester


View raw message