Hello Fred,
fred said:
I have a number of objects that I need converted to XML. In one case
I want a verbose dump to XML, all members included. In another case I
want a brief dump to XML, only some of the members included.
What would be a good pattern to use here, where I can query an {X} to
do the verbose or brief XML dump of an object for me?
Sounds pretty much like you want the Visitor Pattern, though it is maybe
slightly of an overkill for this relatively small use-case of having two
Visitors only. In any case it is best be to move this non functional concern
away from the model object(s).
Possible implementation example:
// pseudo code!
class Model1 {
private String attribute1;
private int attribute2;
private double attribute3;
// ...
}
// brief - exports only few attributes
class ExportToXmlBriefVisitor extends AbstractVisitor {
public visitModel1(Model1 model) {
xml.append(model.getAttribute1());
}
}
// verbose - exports the full model
class ExportToXmlVerboseVisitor extends ExportToXmlLiteVisitor {
public visitModel1(Model1 model) {
super.visitModel1(model);
xml.append(model.getAttribute2());
xml.append(model.getAttribute3());
}
}
Visitor example
http://perfectjpattern.sourceforge.net/dp-visitor.html but
note it is not the classic implementation.
Alternatively you may want to use XStream:
http://xstream.codehaus.org/tutorial.html converting to XML is a one liner
i.e. String xml = new XStream().toXml(new Model1());
then you could just use xslt to process the output xml removing different
selected attributes using the xslt "Identity Transform"
http://en.wikipedia.org/wiki/Identity_transform#Remove_Named_Element_Transform_Using_XSLT
HTH,
Best regards,
Giovanni