Hi Jeff,

On Mon, 2006-06-12 at 08:04 -0700, Jeff Marendo wrote:
> Hello,
>   
>   Would anyone be able to tell me how to structure an XML rules file so  that 
> the Digester can create objects (from the example file below) and  store them 
> into a Map as opposed to a Collection?
>   
>   <?xml version="1.0" encoding="UTF-8"?>
>   <user>
>       <id>doej01</id>
>       <demographic-info>
>               <firstName>John</firstName>
>               <lastName>Doe</lastName>
>       </demographic-info>

[snip]
>   
>   I want to store the User instance in a Map and use the value in the  "id" 
> element as the key. 

I assume you've really got something like:
 <users>
   <user>
     <id>...</id>
     ...
   </user>
   <user>
     <id>...</id>
     ...
   </user>
  </users>

If user is the root level, then you've not got a lot of object in the
map :-)

This won't be trivial to do, because the key to use is embedded within
the user element. Remember that Digester is just a simple layer over
SAX, so it doesn't "look ahead" or "look behind"; data must be processed
when it is encountered.

The best solution would be to simply *not* use a map. If you instead
declare:
 public class Users {
   private Map<User> userMap = new HashMap<User>();

   public void addUser(User u) {
     userMap.put(u.getId(), u);
   }

   ...
 }
then the solution is pretty obvious from there.

If you are determined to use a primitive Map, then I think that you'll
need to write a custom Rule class that knows how to add a User to a Map
(ie implements the operation in the addUser method above). The rule's
end method should assume that the top of stack contains a User, the
second-to-top contains the target Map, and do the appropriate put call. 

Writing a custom Rule is really pretty easy and quite "normal";
Digester's built-in rules are really just a starting point.

Unfortunately, invoking a custom rule when using the xmlrules module
isn't easy. It's been a long time since I did it, so I can't even
remember how it is done...

It *might* be possible to get this working with just a CallMethodRule as
documented in the FAQ on the wiki. However having the pattern for call
parameters match stuff at a different level from the element the call
occurs on can have unexpected interactions with other CallMethodRule
rules; it's better avoided.
  http://wiki.apache.org/jakarta-commons/Digester/FAQ

Regards,

Simon


---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to