RPI/Mathactivity/XML/Sample Parser
< RPI | Mathactivity | XML
Jump to navigation
Jump to search
import xml.dom.minidom #XML handling by DOM import sys, os #To check if the settings file is already there import string
class SettingsParser: def __init__(self, filepath): if os.path.exists(filepath): #Parse and dig out the levels dom = xml.dom.minidom.parse(filepath) di = self.__getLevels(dom) #Figure out what level problems we should give self.level = self.__processLevel(di) else: pass #First time it's been run, need to launch tutorial somehow, also get and set colors def __getLevels(self, dom): """Parses the tree for <level> tags, returning both the number of the level and the percent success this user has had.""" levels = [] percents = [] tries = [] #Loop over the nodes we want (2nd tier from root) for node in dom.childNodes[0].childNodes: #If it's not a text node and it's the right type, let's get to work if node.nodeType == node.ELEMENT_NODE and node.localName == "level": #Grab the level number and convert to int for returning levels.append(int(node.getAttribute("num"))) stri = node.firstChild.data.lstrip().split() for word in stri: if word.find('%') != -1: word = float(word[0:-1]) percents.append(word) else: word = int(word) tries.append(word) dic = self.__setupDictionary(levels, percents, tries) return dic def __processLevel(self, dic): """Works out at which level problem the game should start.""" level = 0 for elem in dic.keys(): #If we're over the percentage and have tried enough times, skip the level if dic[elem][0] > 75 and dic[elem][1] > 10: level+=1 return level def __setupDictionary(self, levels, percents, tries): dic = {} for i in range(len(levels)): dic[i] = [percents[i], tries[i]] return dic
XML Format this is to parse:
<settings> <level> #% //Percent successful at this level # //Number of tries at this level </level> </settings>