public void testLibraryBook() throws SAXException, IOException
{
Digester digester = new Digester();
ClassLoader classLoader = PersistenceHandlerFactory.class.getClassLoader();
URL resource = classLoader.getResource("library.xml");
assertNotNull("Resource should not be null!!", resource);
digester.addObjectCreate("Library", HashMap.class);
digester.addCallMethod("Library/Book", "put", 2);
digester.addRule("Library/Book", new StringObjectCreateRule(String.class, "title"));
digester.addCallParam("Library/Book", 0, true);
digester.addRule("Library/Book", new LibraryBookCreateRule(LibraryBook.class, "title"));
digester.addCallParam("Library/Book", 1, true);
HashMap map = (HashMap)digester.parse(resource.toString());
assertNotNull("Hash map should not be null!!", map);
assertEquals("Based on the xml file, map should have size of 6", 6, map.size());
}
public class LibraryBookCreateRule extends ObjectCreateRule
{
private String key;
public LibraryBookCreateRule(Class aClass, String key)
{
super(aClass);
this.key = key;
}
public void begin(String s, String s1, Attributes attributes) throws Exception
{
LibraryBook book = new LibraryBook(attributes.getValue(key));
super.getDigester().push(book);
}
}
public class LibraryBook
{
private String title;
public LibraryBook(String title)
{
this.title = title;
}
public String getTitle()
{
return title;
}
}
Using library.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Library>
<Book title="The Firm"/>
<Book title="The Cat in the Hat"/>
<Book title="Green Eggs and Ham"/>
<Book title="Object Cobol"/>
<Book title="Anne of Green Gables"/>
<Book title="Smoke 'Em If Ya Got 'Em"/>
</Library>
At 03:04 PM 2/10/2003 -0800, you wrote:
I'm really embarrassed after posting a HowTo on populating a map, but I've found that it's not as clear as I thought it was. I know how to do it with the following example:<?xml version='1.0'?> <map> <key name='The key'/> <value name='The value'/> </map> But how to do it with this? <?xml version='1.0'?> <map> <key name='KeyA'/> <value name='ValueA'/> <key name='KeyB'/> <value name='ValueB'/> </map> CallMethodRule is only invoked at the end of <map>, so you can't call it twice, once for each key, value pair. The situation I have that I actually need to solve looks more like this: <Library> <Book title="The Firm" /> <Book title="The Cat in the Hat" /> </Library> I would want Library to be a HashMap with titles for keys and Book objects for values. You can't use a CallMethodRule on Book because the put() method belongs to Library, not Book. Help? BTW, I realize you can do this by creating proxy objects that call put() for you. That's inelegant IMHO and I was hoping that Digester 1.4 had solved this issue. K.C.
--------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
