Java Reference
In-Depth Information
if (pd.length > 0){
returnValue.append("<" + name + ">");
for (int i = 0; i < pd.length; i++) {
returnValue.append(getProp(o, pd[i]));
}
returnValue.append("</" + name + ">");
} else {
returnValue.append("<" + name + "/>");
}
} else {
throw new ClassCastException("Class " + o.getClass().getName() +
" is not compatible with " + sourceClass.getName());
}
return returnValue.toString();
}
private String getProp(Object o, PropertyDescriptor pd)
throws Exception {
StringBuffer propValue = new StringBuffer("");
Method m = pd.getReadMethod();
Object ret = m.invoke(o);
if(null == ret){
propValue.append("<" + pd.getName() + "/>");
}else{
propValue.append("<" + pd.getName() + ">");
propValue.append(ret.toString());
propValue.append("</" + pd.getName() + ">");
}
return propValue.toString();
}
}
This sample class can be used to easily take a bean and convert it to an XML frag-
ment instead of an XML document. Here is an example:
XmlReflector xr = new XmlReflector(Account.class, "account");
xmlList = sqlMap.queryForList("Account.getAll", null);
StringBuffer sb = new StringBuffer(
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?><accounts>");
for (int i = 0; i < xmlList.size(); i++) {
sb.append(xr.convertToXml(xmlList.get(i)));
}
sb.append("</accounts>");
Using this technique to process a large set of records would be very expensive in
terms of memory—there would be a list of objects in memory, as well as the string
buffer used to build the XML document. In section 6.3, we revisit this example as
we look at more effective ways to manage larger results.
Search WWH ::




Custom Search