What design patterns should you use when writing a parser?

I am writing an XSD parser that will be used to create asp.net controls on a form according to the parsed XSD.

The XSD is loaded from some place (for example, from a database) into an XsdSchema object, and then using .NET (Object Object Model) classes to read the elements of this schema to create a list of controls to be displayed on the form.

What templates do you think are the best to use in this scenario?

(Currently, I have created classes to represent different types of controls - text, date, list, etc., and the xsd parser class has a method that returns a list of these classes according to the parsed XSD.

These "Ui Element" classes were created to somehow not bind the parser to the asp.net layer)

I want to write a parser in a smart way according to some design patterns for easier changes in the future.

Thank.

+3


source to share


1 answer


TL; DR: Visitor template (double submit) and Intepreter template (recursive function) can be used to translate trees (composite template), in your case, form element tree to UI control tree. Here's a clever article about it .

When parsing, it can be helpful to think in terms of trees rather than lists (your list of controls most likely has a parent control, so it is actually a tree). In a nutshell, a tree is a recursive data structure - a node with a scalar identifier and a list of children that point to other nodes, whose children also point to other nodes, etc.

XML can be thought of as a serialization of a tree (actually a graph, but a tree is a general special case), and therefore can XSD. So let's say the XSD contains a tree of form elements that needs to be translated into a tree of user interface elements.

This can be done by traversing the form tree - listing the nodes in some order, creating a UI control for each node, and creating a UI control tree.



Two patterns that come to mind here are Visitor (double dispatch) and Intepreter (recursive function). Here is some tutorial - it's in Java that can be translated to C #.

Update. A good description of the visitor pattern applied to parse trees:

How do I write a visitor pattern for an abstract syntax tree in Python?

Each node in your ACT needs to implement an accept () method (NOT a visit () method). The method accepts a visitor object as an argument. In the implementation of this accept () method, you call the visit () method of the visitor object (there will be one for each AST node type; in Java, you will be using parameter overloading in Python, I suppose you can use different visit methods _ * ()) ...

+1


source







All Articles