You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@commons.apache.org by Jason Vinson <ja...@semagix.com> on 2004/12/10 18:25:16 UTC
[digester] Parsing Attributes of a Topic Map
We have a consultant who is lobbying for a Topic Map format for a
business solution. The following is a simplified example:
<myCheck>
<entity>
<items type="EntityName">
<item name="FirstName" value="Joe"/>
<item name="MiddleName" value=""/>
<item name="LastName" value="Blow"/>
</items>
<item name="PhoneNumber" value="123-456-7890"/>
</entity>
<entity>
.
(any number of entities here)
.
</entity>
</myCheck>
I want to digest this into an object with the following format:
public class Entity {
setFirstName(String fName);
setMiddleName(String mName);
setLastName(String lName);
setPhoneNumber(String phoneNo);
}
So I struggled a bit and came up with this:
Digester digester = new Digester();
digester.addObjectCreate("myCheck", ArrayList.class);
digester.addObjectCreate("myCheck/entity", clazz);
digester.addRule("myCheck/entity/item", new addAttributeSetter());
digester.addRule("myCheck/entity/items/item", new addAttributeSetter());
// Add all "entities"
digester.addSetNext("myCheck/entity", "add");
theList = (List) digester.parse(new StringReader(xml));
with an inner class "addAttributeSetter" with the following:
public void begin(String namespace, String name, Attributes attribs) {
try {
String theVal = attribs.getValue("value");
String theName = StringUtils.uncapitalize(attribs.getValue("name"));
Object obj = digester.peek();
BeanUtils.setProperty(obj, theName, theVal);
} catch (Exception e) {
log.error(e);
}
}
My question is this - There must be an easier way to do this :)
It was way too easy to create this custom rule, which makes me wonder if
there is something similar already in place that I haven't found.
Any comments or pointers are welcomed,
Jason