I’m trying to create a simple XML parser where each different XML schema has it’s own parser class but I can’t figure out what the best way is. What I in effect would like to do is something like this:
in = sys.stdin
xmldoc = minidom.parse(in).documentElement
xmlParser = xmldoc.nodeName
parser = xmlParser()
out = parser.parse(xmldoc)
I’m not also quite sure if I get the document root name correctly, but that’s the idea: create an object of a class with similar name to the document root and use the parse() function in that class to parse and handle the input.
What would be the simplest way to achieve this? I’ve been reading about introspection and templates but haven’t been able to figure this out yet. I’ve done a similar thing with Java in the past and AFAIK, Ruby also makes this simple. What’s the pythonian way?
As pointed out by Mark in his comment, to get a reference to a class that you know the name of at runtime, you use getattr.
Below is a corrected version of your pseudo-code.
getattr will return an AttributeError if the attribute doesn’t exist, so you can wrap the call in a try…except or pass a third argument to getattr, wich will be returned if the attribute isn’t found.