import os from SupportedType import SupportedType from xml.etree.ElementTree import ElementTree class XmlDataParser: """ This class parses all of the information in the config file, and makes it available through various methods. """ def __init__(self, xml_file_path): """ We build a list of supported mimetypes upon instantiation. """ self.__supported_types = [] xml_doc = ElementTree() xml_doc.parse(xml_file_path) supported_type_elements = xml_doc.findall('supported_type') # For each supported_type element, we build a SupportedType # object and add it to our __supported_types list. for current_node in supported_type_elements: name = self.GetChildrenText(current_node, 'name')[0] descriptions = self.GetChildrenText(current_node, 'description') extensions = self.GetChildrenText(current_node, 'extension') template_files = self.GetChildrenText(current_node, 'template_file') template_data = self.GetChildrenText(current_node, 'template_data') current_type = SupportedType(name = name, extensions = extensions) if (len(descriptions) > 0): current_type.description = descriptions[0] if (len(template_files) > 0): # Allow for relative paths in the template field root_dir = os.path.dirname(xml_file_path) current_type.template_file = os.path.join(root_dir, template_files[0]) if (len(template_data) > 0): current_type.template_data = template_data[0] self.__supported_types.append(current_type) return def GetAllExtensions(self): all_extensions = [] for current_type in self.__supported_types: for extension in current_type.extensions: all_extensions.append(extension) return all_extensions def GetTemplateByExtension(self, extension): """ Get the (x)html template which corresponds to a mimetype having the supplied extension. """ for current_type in self.__supported_types: for current_extension in current_type.extensions: if (current_extension.lower() == extension.lower()): return current_type.GetTemplate() return None def GetNameByExtension(self, extension): """ Get the name of the mimetype to which a particular extension belongs. """ for current_type in self.__supported_types: for current_extension in current_type.extensions: if (current_extension.lower() == extension.lower()): return current_type.name return None def GetChildrenText(self, node, child_tag_name): """ Find the text of all children of node having child_tag_name. For example, if we were passed a supported_type for node, we might want to find the text of all extension elements. """ children_text = [] children = node.findall(child_tag_name) for child_node in children: children_text.append(child_node.text) return children_text