Example #1
0
	def set(self, module, name, value, extra_attrs={}):
		"""
		Sets a variable to specified value.

		@param module: Module where the variable should be set
		@param name: Name of the variable
		@param value: Value to assign to the variable
		@type value: C{str} or C{unicode} or C{int} or C{float} or C{bool} or 
		C{list} or C{dict}
		@param extra_attrs: Extra attributes to be stored in the XML-file
		@type extra_attrs: C{dict}
		"""
		if not self._initialized:
			self.load()
			self._initialized = True
		
		if not isinstance(name, str) and not isinstance(name, unicode):
			raise AttributeError("SimpleXMLSerializer.set(): Invalid type for "
								 "name argument.")

		moduleTree = self._getModuleTree(module)
		e_type = "str"

		if isinstance(value, bool): # This must be before int
			e_type = "bool"
			value = str(value)
		elif isinstance(value, int):
			e_type = "int"
			value = str(value)
		elif isinstance(value, float):
			e_type = "float"
			value = str(value)
		elif isinstance(value, unicode):
			e_type = "unicode"
			value = unicode(value)
		elif isinstance(value, list):
			e_type = "list"
			value = self._serializeList(value)
		elif isinstance(value, dict):
			e_type = "dict"
			value = self._serializeDict(value)
		else:
			e_type = "str"
			value = str(value)

		for e in moduleTree.getchildren():
			if e.tag != "Setting": continue
			if e.get("name", "") == name:
				e.text = value
				break
		else:
			attrs = {"name":name, "type":e_type}
			for k in extra_attrs:
				if k not in attrs:
					attrs[k] = extra_attrs[k]
			elm = ET.SubElement(moduleTree, "Setting", attrs)
			elm.text = value
Example #2
0
	def _getModuleTree(self, module):
		"""
		Returns a module element from the XML tree. If no module with the 
		specified name exists, a new element will be created.

		@param module: The module to get from the settings tree
		@type module: C{string}
		"""
		if not isinstance(module, str) and not isinstance(module, unicode):
			raise AttributeError("Settings:_getModuleTree: Invalid type for "
								 "module argument.")

		for c in self._root_element.getchildren():
			if c.tag == "Module" and c.get("name", "") == module:
				return c

		# Create module
		return ET.SubElement(self._root_element, "Module", {"name":module})