I have a tree data structure where each node describes how to use its child nodes, and this tree is stored in a standard data format - XML for now. However, there are a large number of different kinds of nodes, and I shouldn't have to update the core code that reads in the XML and converts it to software objects every time I want to add a new node type.

My solution is to use an interface in the core reader code. Each node object will have an associated reader object that implements the interface, and when the core reader runs into a node X, it will go fetch X's associated reader object by name out of a global data structure that gets populated on program startup. The core reader will have the specific reader object read in the node; the specific reader object can likewise easily call back into the general reader code. If someone authors their own node types and readers (i.e. dynamic library), they could update the global table and presto, everything keeps working.

The issue is that I don't know if there is a more canonical solution to this problem. Looking up objects by string/id/whatever seems fishy, but I can't see another way to convert from data to code. I'm also wondering if having the algorithms that run on this data structure (once it's loaded into software) implement a similar mechanism would also be a good idea; new nodes could update existing algorithms without needing to rewrite them.

Update to clarify that I'm converting from XML to software object, not parsing the syntax of XML itself.

  • 3
    Generally, having modular parsing like that is asking for trouble (since the different modules can specify conflicting/ambiguous grammars). Are you sure you really mean "parser"? – Telastyn Oct 26 '19 at 3:24
  • I'm using a library to parse XML at the moment, but the pattern would be the same for JSON or anything else. I'm not writing an XML parser per se. – GraphicsMuncher Oct 26 '19 at 8:39
  • Are you perhaps using the word "parsing" in a unconventional way? Parsing normally describes the processing of textual inputs which you say is done using a library at the moment. Maybe you need to clarify that. – Hans-Martin Mosner Oct 26 '19 at 16:31

Yeah this seems like a pretty standard way of doing things.

Check out how json.net allows you to add custom type serialisers for example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.