Loading OOP structure from XML--how to design code

thbl3004

New Member
I have a structure consisting of a number of classes, kind of like so:
  • Document
    • Track (each document can have multiple tracks)Clip (each track can have multiple clips)
  • (Other types may be added in the future)
I'm storing these documents as XML, like so:<Document><Track><Clip>...</Clip></Track></Document>In each class, I have a toXML() method, which describes its contents in XML form. Document::toXML() is responsible for calling toXML() on its children, and combining the result.This way, saving is quite trivial and easy to extend in my opinion.But now I'm having trouble with how to design the loading code.There are two ways I can think of:1: Huge if-statement in Document::fromXML(), something like:\[code\]// Pseudo codefor each element { if element.name == "Track" createTrack(element) if element.name == "Clip" createClipOnLastTrack(element) // .. more statements for new types}\[/code\]2: A "loader" class which keeps of loading methods for all types, something like:\[code\]// Track.fromXML will be responsible for calling Clip.fromXMLLoader.register("Track", &Track.fromXML)Loader.register("OtherType", &OtherType.fromXML)// More register() calls for new typesfor each element { // Call appropriate method based on tag name Loader.load(element.name, element)}\[/code\]I don't really like #1, it feels clumsy. #2 feels better, but I'm not sure if it's a good design.Is it? Is there some other common/popular way of translating an XML document to a set of actual object instances?
 
Back
Top