def lensesRSS(): lensesQuery = session.query(Lens).all() lenses = ET.Element('lenses') for i in lensesQuery: lens = ET.SubElement(lenses, 'lens') id = ET.SubElement(lens, 'id').text = str(i.id) name = ET.SubElement(lens, 'name').text = i.name brand = ET.SubElement(lens, 'brand').text = i.brand style = ET.SubElement(lens, 'type').text = i.style zoom_min = ET.SubElement(lens, 'zoom_min').text = \ str(i.zoom_min) zoom_max = ET.SubElement(lens, 'zoom_max').text = \ str(i.zoom_max) aperture = ET.SubElement(lens, 'aperture').text = \ str(i.aperture) price_per_day = ET.SubElement(lens, 'price_per_day').text = \ str(i.price_per_day) price_per_week = ET.SubElement(lens, 'price_per_week').text = \ str(i.price_per_week) price_per_month = ET.SubElement(lens, 'price_per_month').text = \ str(i.price_per_month) print prettify(lenses) return prettify(lenses)
def writexml(self, output_path = ''): if output_path: with open( os.path.join(output_path , "mapringinfo.xml") , "w") as f: f.write(prettify(self.TestName)) else: with open( os.path.join(self.ringpath , "mapringinfo.xml") , "w") as f: f.write(prettify(self.TestName)) return prettify(self.TestName)
def generateXML(self, tag): xml = Element('nfctag') xml.set('type', tag.type) uid = SubElement(xml, 'uid') uid.text = str(tag.uid).encode('hex') atq = SubElement(xml, 'atq') atq.text = str(tag.atq) sak = SubElement(xml, 'sak') sak.text = str(tag.sak) timestamp = SubElement(xml, 'timestamp') timestamp.text = str(tag.timestamp) reader = SubElement(xml, 'reader') reader.text = os.uname()[1] if tag.ndef: ndef = SubElement(xml, 'ndef') version = SubElement(ndef, 'version') version.text = str(tag.ndef.version) readable = SubElement(ndef, 'readable') readable.text = str(tag.ndef.readable) writeable = SubElement(ndef, 'writeable') writeable.text = str(tag.ndef.writeable) capacity = SubElement(ndef, 'capacity') capacity.text = str(tag.ndef.capacity) length = SubElement(ndef, 'length') length.text = str(tag.ndef.length) message = SubElement(ndef, 'message') message.text = str(tag.ndef.message).encode('hex') return prettify(xml)
def test5(): top = Element('transactions') attributes1 = {'id': '123456'} top.attrib = attributes1 attributes2 = {'sym': 'Test2', 'amount': '5000', 'limit': '1000'} SubElement(top, 'order', attributes2) return prettify(top) #err
def train(self, training_data_filelist, tree_depth, ntrees): self.tree_depth = tree_depth self.tree_list = [RegressionTree(tree_depth) for _ in range(ntrees)] nimages = len(training_data_filelist) subsample_size = int(round(self.subsample_frac*nimages)) if self.saveXML: # make a directory to contain trained tree info: # TODO: ask the user if they want to overwrite files in this dir or not. self.training_result_dir = './random_forest_params/depth%intrees%inimages%i' % (tree_depth, ntrees, subsample_size) if not os.path.exists(self.training_result_dir): os.makedirs(self.training_result_dir) for idx,t in enumerate(self.tree_list): # create each tree w/ training data: if self.subsample_frac == 1.0: t.cluster_images(training_data_filelist) else: filelist_subsamp = random.sample(training_data_filelist, subsample_size) t.cluster_images(filelist_subsamp) # write XML parameter file for each tree (more human-readable than elemtree.write()): if self.saveXML: with open(self.training_result_dir+'/tree%i.xml' % (idx),'w') as f: f.write(prettify(t.elemtree.getroot())) # output trained tree result for graph visualization: if self.exportgv: t.export_graphviz_file(idx, self.training_result_dir)
def get_xml(): sheets = SubElement(root, str("sheet_" + str(num)), {'id': str(name)}) # for i in range(10): for i in range(sheet.nrows): is_data = sheet.cell(i, 0).value def get_data(col): data = str(sheet.cell(i, col).value) if "\n\n" in data: data = data.replace("\n\n", ", ") return data if "A" == is_data or "B" == is_data or "-" == is_data: element = SubElement(sheets, str("element_" + str(i)), { 'id': get_data(14), 'depth': get_data(22) }) contents = [ SubElement(element, str("content_" + str(j)), {'id': str(title_list[j])}) for j in range(len(title_list)) ] for j in range(len(title_list)): contents[j].text = get_data(j) #### Type it later. f = open("/Users/sho/Documents/new.xml", 'w', encoding='utf8') f.write(prettify(root))
def transaction_response(response): top=Element('results') for child in response: if child.type=='order': if (child.success): attributes={"sym":child.symbol, "amount":str(child.amount), "limit":str(child.limit_price), "id":str(child.trans_id)} node=SubElement(top,'opened',attributes) else: attributes={"sym":child.symbol, "amount":str(child.amount), "limit":str(child.limit_price)} node=SubElement(top,'error',attributes) node.text=child.err if child.type == 'query' or child.type == 'cancel': attributes={"id":str(child.trans_id)} if(child.success): if child.type=='query': node=SubElement(top,'status',attributes) if child.type=='cancel': node=SubElement(top,'canceled',attributes) for grand_child in child.trans_resp: if(grand_child.status=='open'): sub_attributes = {"shares": str(grand_child.shares)} subnode = SubElement(node, 'open', sub_attributes) if(grand_child.status=='cancelled'): sub_attributes = {"shares": str(grand_child.shares), "time": str(grand_child.time)} subnode = SubElement(node, 'canceled', sub_attributes) if(grand_child.status=='executed'): sub_attributes = {"shares": str(grand_child.shares), "price": str(grand_child.price), "time": str(grand_child.time)} subnode = SubElement(node, 'executed', sub_attributes) else: node=SubElement(top,'error',attributes) node.text=child.err return prettify(top)
def test11(): top = Element('transactions') attributes1 = {'id': '234567'} top.attrib = attributes1 attributes2 = {'id': '2'} SubElement(top, 'query', attributes2) return prettify(top)
def write_generated_namelist(nml_file=None, nml_dict=None): """ This will write a set of previously generated namelists to a file """ if not nml_file: # No file specified return None elif not nml_dict: # No namelist specified return None else: top = Element('top') namelists = {} children = {} for key in nml_dict.keys(): tmp = Element('namelist',name=key) for i in nml_dict[key]: children[i] = Element('parameter', name=i, type=nml_dict[key][i].type) default = SubElement(children[i],'default') default.text = str(nml_dict[key][i].default) desc = SubElement(children[i],'description') desc.text = nml_dict[key][i].description tmp.extend(children.values()) top.append(tmp) children = {} # Open file with file(nml_file,'w') as f: f.write(prettify(top)) return top
def train(self, training_data_filelist, tree_depth, ntrees): self.tree_depth = tree_depth self.tree_list = [RegressionTree(tree_depth) for _ in range(ntrees)] nimages = len(training_data_filelist) subsample_size = int(round(self.subsample_frac * nimages)) if self.saveXML: # make a directory to contain trained tree info: # TODO: ask the user if they want to overwrite files in this dir or not. self.training_result_dir = './random_forest_params/depth%intrees%inimages%i' % ( tree_depth, ntrees, subsample_size) if not os.path.exists(self.training_result_dir): os.makedirs(self.training_result_dir) for idx, t in enumerate(self.tree_list): # create each tree w/ training data: if self.subsample_frac == 1.0: t.cluster_images(training_data_filelist) else: filelist_subsamp = random.sample(training_data_filelist, subsample_size) t.cluster_images(filelist_subsamp) # write XML parameter file for each tree (more human-readable than elemtree.write()): if self.saveXML: with open(self.training_result_dir + '/tree%i.xml' % (idx), 'w') as f: f.write(prettify(t.elemtree.getroot())) # output trained tree result for graph visualization: if self.exportgv: t.export_graphviz_file(idx, self.training_result_dir)
def buildManifest( PartName, Path, Title): with open('/Users/kauwers/Desktop/Module1-2/module_data.xml', 'a') as writeFile: session = ET.Element('session') session.set('name', "Part "+PartName) session.set('path', Path) session.set('title', Title) prettyData = prettify(session) writeFile.write(prettyData)
def create_request(): top=Element('create') attributes1={"id":str(random.randint(1,10001)),"balance":str(random.randint(1,10001))} SubElement(top, 'account', attributes1) attributes2={"sym":randomword(3)} node=SubElement(top,'symbol',attributes2) attributes3={"id":str(random.randint(1,10001))} node1=SubElement(node,'account',attributes3) node1.text=str(random.randint(1,10001)) return prettify(top)
def test6(): top = Element('transactions') attributes1 = {'id': '98765'} top.attrib = attributes1 attributes2 = {'sym': 'Test2', 'amount': '5000', 'limit': '1000'} SubElement(top, 'order', attributes2) attributes3 = {'id': '2'} SubElement(top, 'query', attributes3) attributes4 = {'id': '3'} SubElement(top, 'cancel', attributes4) return prettify(top) #err
def transaction_request(): top=Element('transactions') attributes1={'id':str(random.randint(1,10001))} top.attrib=attributes1 attributes2={'sym':randomword(3),'amount':str(random.randint(-10000,10001)),'limit':str(random.randint(1,10001))} SubElement(top,'order',attributes2) attributes3={'id':str(random.randint(1,10001))} SubElement(top,'query',attributes3) attributes4={'id':str(random.randint(1,10001))} SubElement(top,'cancel',attributes4) return prettify(top)
def create_dc_xml(file, destination): with open(file, 'r') as csvfile: csvreader = csv.DictReader(csvfile) xml = create_base_xml(csvreader.fieldnames) for row in csvreader: for key, value in row.items(): if key.startswith('dc:') or key.startswith('dcterms:') or \ key.startswith('cld:') or key.startswith('marcrel:'): child = SubElement(xml, key) child.text = value mydata = prettify(xml) filename = f'{row["dcterms:identifier"]}.xml' print_xml(os.path.join(destination, filename), mydata)
def lensXML(lens_id): query = session.query(Lens).filter_by(id=lens_id).one() lens = ET.Element('lens') id = ET.SubElement(lens, 'id').text = str(query.id) name = ET.SubElement(lens, 'name').text = query.name brand = ET.SubElement(lens, 'brand').text = query.brand style = ET.SubElement(lens, 'type').text = query.style zoom_min = ET.SubElement(lens, 'zoom_min').text = \ str(query.zoom_min) zoom_max = ET.SubElement(lens, 'zoom_max').text = \ str(query.zoom_max) aperture = ET.SubElement(lens, 'aperture').text = \ str(query.aperture) price_per_day = ET.SubElement(lens, 'price_per_day').text = \ str(query.price_per_day) price_per_week = ET.SubElement(lens, 'price_per_week').text = \ str(query.price_per_week) price_per_month = ET.SubElement(lens, 'price_per_month').text = \ str(query.price_per_month) print prettify(lens) return prettify(lens)
def saveObjectsDataToXML(objs, fpath): from xml.etree.ElementTree import Element, ElementTree, fromstring from ElementTree_pretty import prettify from mcColl import getObjectValue root = Element("root") children = [] for o in objs: # print ("obj:{}\n\tmat:{}\n\tparent:{}".format(o.Name, o.Material, o.Parent.Name)) children.append( Element('item', name=str(getObjectValue(o, "name")), parent=str(getObjectValue(o, "parent.name")), material=str(getObjectValue(o, "active_material.name")))) root.extend(children) #~ add children in to root node root = fromstring(prettify(root)) #~format xml print("saveObjectsDataToXML > Root:\n\t", root) ElementTree(root).write(fpath, encoding="UTF-8", method="xml")
def test1(): top = Element('create') attributes1 = {"id": '123456', "balance": '1000000'} SubElement(top, 'account', attributes1) attributes2 = {"id": '234567', "balance": '1000000'} SubElement(top, 'account', attributes2) attributes3 = {"id": '01234', "balance": '1000000'} SubElement(top, 'account', attributes3) attributes4 = {"sym": "Test1"} node = SubElement(top, 'symbol', attributes4) attributes5 = {"id": '123456'} node1 = SubElement(node, 'account', attributes5) node1.text = '100000' attributes6 = {"sym": "Test3"} node = SubElement(top, 'symbol', attributes6) attributes7 = {"id": '123456'} node1 = SubElement(node, 'account', attributes7) node1.text = '100000' attributes8 = {"sym": "Test2"} node = SubElement(top, 'symbol', attributes8) attributes9 = {"id": '234567'} node1 = SubElement(node, 'account', attributes9) node1.text = '100000' attributes10 = {"sym": "Test2"} node = SubElement(top, 'symbol', attributes10) attributes11 = {"id": '01234'} node1 = SubElement(node, 'account', attributes11) node1.text = '100000' attributes12 = {"id": '123456', "balance": '1000000'} #err SubElement(top, 'account', attributes12) attributes13 = {"sym": "Test2"} node = SubElement(top, 'symbol', attributes13) attributes14 = {"id": '98765'} node1 = SubElement(node, 'account', attributes14) #err node1.text = '100000' return prettify(top)
def saveObjectsDataToXML(objs, fpath): from xml.etree.ElementTree import Element, ElementTree, fromstring from ElementTree_pretty import prettify from mcPoly import isGeometryClass root = Element("root") children = [] for o in objs: if isGeometryClass(o): # print ("obj:{}\n\tmat:{}\n\tparent:{}".format(o.Name, o.Material, o.Parent.Name)) children.append( Element('item', name=o.Name, parent=o.Parent.Name if o.Parent.Name != "Scene Root" else "None", material=o.Material.GetName() if o.Material else "None" ) ) root.extend(children) #~ add children in to root node root = fromstring(prettify(root)) #~format xml ElementTree(root).write(fpath, encoding="UTF-8", method="xml")
def dataToXml(data): rules = rule(data) inputs = inOut(data,'input') outputs = inOut(data,'output') arrayData = [{'name': 'Mark', 'range': '[0 21]', 'memship': [{'name': 'low', 'type': 'trapmf', 'amount': '[0 10 2 31]'}, {'name': 'high', 'type': 'trimf', 'amount': '[0 10 2 35]'}]}, {'name': 'sysmark', 'range': '[0 22]', 'memship': [{'name': 'hard', 'type': 'trimf', 'amount': '[0 10 2 32]'}]}] lenIn = len(inputs) lenOut = len(outputs) lenRule = len(rules) Fuzzy = Element('Fuzzy') comment = Comment('Xml File For Mirab Fuzzy Control System') Fuzzy.append(comment) Input = SubElement(Fuzzy,'Input', inputnums=str(lenIn)) Output = SubElement(Fuzzy,'Output', outputnume=str(lenOut)) Rule = SubElement(Fuzzy,'Rule', rulenums=str(lenRule)) # memshipFunctions = len(arrayData[0]['memship']) # print(memshipFunctions) # print(arrayData) for i, val in enumerate(outputs, 1): output = SubElement(Output,'output'+str(i),outputmems=str(len(val['memship'])) ,name=val['name'], range=val['range']) for j, value in enumerate(val['memship'], 1): MF = SubElement(output, 'MF'+str(j), name=value['name'], type=value['type']) MF.text = value['amount'] for i, val in enumerate(inputs, 1): input = SubElement(Input,'input'+str(i),inputmems=str(len(val['memship'])) ,name=val['name'], range=val['range']) for j, value in enumerate(val['memship'], 1): MF = SubElement(input, 'MF'+str(j), name=value['name'], type=value['type']) MF.text = value['amount'] for i, val in enumerate(rules, 1): rule = SubElement(Rule, 'rule'+str(i)) rule.text = val FuzzyFile = prettify(Fuzzy) return FuzzyFile # a = ElementTree(Fuzzy).write(sys.stdout, method='xml')
def create_response(create):#create=Create_obj() top=Element('results') for child in create: if child.type=='account': if child.created: attributes={"id":str(child.account_id)} node=SubElement(top,'created',attributes) else: attributes={"id":str(child.account_id)} node=SubElement(top,'error',attributes) node.text=child.err elif child.type=='position': if child.created: attributes={"id":str(child.account_id),"sym":child.symbol} node=SubElement(top,'created',attributes) else: attributes={"id":str(child.account_id),"sym":child.symbol} node=SubElement(top,'error',attributes) node.text=child.err return prettify(top)
def salidaxml(self): top = Element('Matrices') comment = Comment('Generado por Selvin') top.append(comment) """ child = SubElement(top, 'Matriz', nombre="loquesea", m="1", n="2") child2 = SubElement(child, 'dato', x="1", y="2") child2.text = '5' """ for i in range(LMatResult.tamanio()): child=SubElement(top,'matriz',nombre=str(LMatResult.getLista(i).getNombreMatriz())+'_salida',n=str(LMatResult.getLista(i).tamFila()),m=str(LMatResult.getLista(i).getNumColumna()),g=str(LMatResult.getLista(i).tamFila())) for j in range(LMatResult.getLista(i).tamFila()): for k in range(LMatResult.getLista(i).getNumColumna()): child2= SubElement(child,'dato',x=str(j+1),y=str(k+1)) child2.text = str(LMatResult.getLista(i).mostrarenfilaycolumna(j,k)) file = open("salida.xml", "w") file.write(str((prettify(top)))) file.close()
def parse_file_info(self): # parse mhw header file to xml, ignore comment, predefined part... # need to modified if mhw header file code structure changes if not self.lines: print('Please read file first\n') return f_ignore = False method_type = 'private' f_method = False f_struct = False # content = Element('content') content.set('file', self.name) current_group = content #init unparsed_index = 0 unparsed_text_id = 0 nest_layer = [] # save current layer nest_layer_num = 0 # count nest layer num saved_enum_name = '' #pretreat texts new_lines = [] for index, line in enumerate(self.lines): line = line.replace('{', '\n{\n') #make sure '{' and '}' be splited line = line.replace('(', ' ( ') line = line.replace(')', ' ) ') # line = line.replace('}','\n}\n') line = line.lstrip() #delete former blank if line.startswith( '__CODEGEN_BITFIELD'): #in case unfinished definition new_lines[-1] = new_lines[-1].strip('\n') + ' ' + line else: line = line.split('\n') new_lines.extend([x.strip() for x in line if x]) #filter blank in the list # print(new_lines[373]) for index, line_clr in enumerate(new_lines): # debug part #print(index) #print('----------------------------------\n') #print(prettify(content)) #------------------------------------------------------- #parse comment part, which can be ignored(cleared) if f_ignore: idx = line_clr.find('*/') if idx == -1: continue else: #comment end f_ignore = False line_clr = line_clr[idx + 2:] if line_clr.startswith('/*'): #comment start f_ignore = True continue # continue may ignore the content and cause some problem if line_clr.find('//') != -1: idx = line_clr.find('//') line_clr = line_clr[:idx] if not line_clr: continue #clear comment part, ignore blank line #-------------------------------------------------------- #------------------------------------------------------ #parse pre-defined parts if line_clr.startswith('#include'): self.includes.add(line_clr[10:-1]) continue elif line_clr.startswith('#'): self.elpredef.add(line_clr[1:]) continue #----------------------------------------------------- #-------------------------------------------- # manage nest layer if line_clr.find('{') != -1: nest_layer.append( current_group ) #enter child layer, problem occurs when unparse function nest_layer_num += 1 if index - unparsed_index == 2: # parse {} in one line but {} are splited before unparsed_index += 1 #idx = line_clr.find('{') #if line_clr[idx+1]: # line_clr = line_clr[idx+1:] #else: continue #-------------------------------------------------------- #-------------------------------------------- #parse datastructure = {'class', 'struct', 'union', 'enum' , 'namespace' } if any([line_clr.startswith(item) for item in self.datastructure]): self.structure_type, self.structure_name, self.super_structure_type, self.super_structure_name = self.get_datastructure( line_clr) new_datastruct_group = SubElement(current_group, self.structure_type) current_group = new_datastruct_group if self.structure_name: current_group.set('name', self.structure_name) if self.super_structure_type: current_group.set('super_structure_type', self.super_structure_type) current_group.set('super_structure_name', self.super_structure_name) continue #------------------------------------------------------------- #------------------------------------------------------------- #parse member_accessors = {'public:', 'protected:', 'private:' } if line_clr in self.member_accessors: member_accessor = line_clr.strip(':') new_group = SubElement(current_group, member_accessor) current_group = new_group nest_layer.append(current_group) nest_layer_num += 1 continue #---------------------------------------------------- #-------------------------------------------- #parse basic_type = {'int', 'bool', 'dword', 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t', 'char'} if any([line_clr.startswith(item) for item in self.basic_type]): self.type, self.basic_name, self.arraysize, self.address, self.prefix, self.value, self.para_name, self.para_type = self.parse_basictype( line_clr) if self.basic_name: new_basic_group = SubElement(current_group, self.type, name=self.basic_name) if self.address: new_basic_group.set('bitfield', self.address) if self.arraysize: new_basic_group.set('arraysize', self.arraysize) if self.para_name: ### Problems!!!! # function definition is not related to current command validator requirement, so this part is unfinished for i, para_name in enumerate(self.para_name): new_func_group = SubElement( current_group, 'FUNCTION', { 'para_name': para_name, 'para_type': self.para_type[i] }) current_group = new_func_group continue #parse datatype above, but with prefix #e.g.: 'static const size_t dwSize = 1;' if any([line_clr.startswith(item) for item in self.prefixset]) and line_clr.find('=') != -1: self.type, self.basic_name, self.arraysize, self.address, self.prefix, self.value, self.para_name, self.para_type = self.parse_basictype( line_clr) #exclude exceptions if self.type not in self.basic_type: break new_basic_group = SubElement(current_group, self.type, name=self.basic_name) if self.address: new_basic_group.set('address', self.address) if self.prefix: new_basic_group.set('prefix', self.prefix) if self.value: new_basic_group.set('value', self.value) continue #------------------------------------------------------------- #------------------------------------------------------------ #pase member inside enum{}, always set value? #suppose set value #e.g. 'FORCEINTRA_ENABLE = 1,' if current_group.tag == 'enum': if line_clr.find('=') != -1: idx = line_clr.find('=') name = line_clr[:idx].strip() value = line_clr[idx + 1:line_clr.find(',')].strip() if current_group.attrib['name'] == saved_enum_name: text_id += 1 else: text_id = 0 enum_member_group = SubElement(current_group, 'text', id=str(text_id)) enum_member_group.set('name', name) enum_member_group.set('value', value) saved_enum_name = current_group.attrib['name'] continue #------------------------------------------------------------ #------------------------------------------------------------ #pase reference member inside struct xxx_CMD{yyy_CMD zzz;} #and constructor xxx_CMD{xxx_CMD();} #only those endwith '_CMD' #e.g. 'VDENC_64B_Aligned_Lower_Address_CMD LowerAddress # 'HUC_VIRTUAL_ADDR_REGION_CMD HucVirtualAddressRegion[16]; ' if line_clr.find('_CMD') != -1: if (current_group.tag == 'struct' and 'name' in current_group.attrib and current_group.attrib['name'].endswith('_CMD') ) or current_group.tag == 'union': if 'name' in current_group.attrib: #1: constructor xxx_CMD{xxx_CMD();} constructor = current_group.attrib['name'] if line_clr.startswith( constructor ) and '(' in line_clr and ')' in line_clr: constructor_group = SubElement( current_group, 'constructor', {'name': constructor}) idx1 = '(' idx2 = ')' line_clr1 = line_clr[line_clr.find(idx1) + 1:line_clr.find(idx2)].strip( ) if line_clr1: constructor_group.set('text', line_clr1) continue #2: otherstruct yyy_CMD zzz; #3: inside union yyy_CMD zzz; # may have exceptions line_clr1 = line_clr.strip().strip(';').strip() item_list = line_clr1.split() otherCMD = item_list[0] if otherCMD.endswith('_CMD'): name = item_list[1] otherCMD_group = SubElement(current_group, 'otherCMD') if re.search('\[\d+\]', name): arraysize = re.search( '\[\d+\]', name)[0].strip('[').strip(']') otherCMD_group.set('arraysize', arraysize) otherCMD_group.set('otherCMD', otherCMD) otherCMD_group.set('name', name) continue #------------------------------------------------------------ #------------------------------------------------------------ # parse 'return xxx;}' and 'return xxx;' # error when former function unparsed if line_clr.startswith('return'): return_value = line_clr.strip('return').strip().strip( ';').strip() return_group = SubElement(current_group, 'return') return_group.set('value', return_value) #------------------------------------------------------------ #------------------------------------------------------------ # manage nest layer, position fixed in the end part if line_clr.find('}') != -1: nest_layer.pop() #exit current layer, return to parent nest_layer_num -= 1 if line_clr.find(';') != -1: #current_group = nest_layer[-1] idx1 = '}' idx2 = ';' line_clr1 = line_clr[line_clr.find(idx1) + 1:line_clr.find(idx2)].strip() # if'};' simply exit current layer, look like struct definition finished if line_clr1: # parse '} DW0;', post-positioned name text = line_clr1 current_group.set('name', text) # if'xxx;}' xxx maybe parsed above, maybe 'return __CODEGEN_OP_LENGTH(uiLength); }' # if unparsed, will lose xxx; line_clr2 = line_clr[:line_clr.find(idx2)].strip() if nest_layer: current_group = nest_layer[-1] continue #------------------------------------------------------------- #------------------------------------------------------------- #consecutive unparsed part save as text #if index-unparsed_index != 1 : # unparsed_text = '' #print(line_clr) #leave function(xx){return xx ;} unparsed unparsed_text = line_clr unparsed_text_id += 1 unparsed_text_group = SubElement(current_group, 'unparsedtext', id=str(unparsed_text_id)) unparsed_text_group.text = unparsed_text #test, see each update xml #print(prettify(content)) #------------------------------------------- #print(prettify(content)) return prettify(content) #test #filename = 'mhw_vdbox_vdenc_hwcmd_g12_X.h' #path = r'C:\Users\jiny\gfx\gfx-driver\Source\media\media_embargo\ult\agnostic\test\gen12\hw\vdbox' #obj = HeaderParser(filename, path) #obj.read_file() #obj.write_xml()
if __name__ == '__main__': from optparse import OptionParser, OptionGroup parser = OptionParser() parser.set_usage("Usage: %prog [options] directory") parser.add_option("-d","--dir", action="store", type="string", dest="directory", help="Top level folder to start scanning from") parser.add_option("-f","--file", action="store", type="string", dest="logfile", help="Output log file (not written to stdout)" ) group = OptionGroup(parser, "Hack Options", "May not function without advanced knowledge") group.add_option("-s","--sql", action="store_true", dest="printSql", help="Output results in SQL INSERT statements instead of XML") group.add_option("-p","--pretty", action="store_true", dest="pretty", help="Print easy to read XML to stdout") parser.add_option_group(group) (options, args) = parser.parse_args() # Argument processing if len(sys.argv) == 2: options.directory = sys.argv[1] if len(sys.argv) < 2: parser.print_help() sys.exit(1) from xml.etree.ElementTree import Element, SubElement import xml.etree.ElementTree as ET from ElementTree_pretty import prettify xmlroot = startXML() startup() writeXML(xmlroot) if options.pretty: print prettify(xmlroot)
def main(argv): from_date = '2013-11-24' to_date = '2013-11-28' username = None device = None title = None xcode = False try: opts, args = getopt.getopt(argv, "f:t:u:d:T:X", ["from", "to", "username", "device", 'Title', 'Xcode' ]) except getopt.GetoptError as e: print_usage() sys.exit(2) for opt, arg in opts: if opt in ('-d', '--device'): device = arg if opt in ('-u', '--username'): username = arg if opt in ('-f', '--from'): from_date = arg if opt in ('-t', '--to'): to_date = arg if opt in ('-T', '--title'): title = arg if opt in ('-X', '--Xcode'): xcode = True if username is None: print "You must provide a username" sys.exit(2) if device is None: print "You must provide a device name" sys.exit(2) if title is None: title = "Trip %s to %s" % (from_date, to_date) root = ET.Element('gpx') root.set('version', '1.0') root.set('creator', 'OwnTracks GPX Exporter') root.set('xmlns', "http://www.topografix.com/GPX/1/0") root.append(Comment('Hi JP')) if not xcode: track = Element('trk') track_name = SubElement(track, 'name') track_name.text = title track_desc = SubElement(track, 'desc') track_desc.text = "Length: xxx km or so" segment = Element('trkseg') track.append(segment) trackpoints = [] waypoints = [] lat1 = None lon1 = None lat2 = None lon2 = None query = Location.select().where( (Location.username == username) & (Location.device == device) & (Location.tst.between(from_date, to_date)) ) query = query.order_by(Location.tst.asc()) for l in query: dbid = l.id topic = l.topic lat = l.lat lon = l.lon dt = l.tst weather = l.weather revgeo = l.revgeo desc = l.waypoint # First point if lat1 is None: lat1 = lat lon1 = lon lat2 = lat lon2 = lon tp = Element('trkpt') tp.set('lat', lat) tp.set('lon', lon) tp_time = SubElement(tp, 'time') tp_time.text = dt.isoformat()[:19]+'Z' tp.append(Comment(u'#%s %s' % (dbid, topic))) trackpoints.append(tp) if xcode: wpt = Element('wpt') wpt.set('lat', lat) wpt.set('lon', lon) waypoints.append(wpt) else: if (weather is not None and revgeo is not None) or (desc is not None): wpt = Element('wpt') wpt.set('lat', lat) wpt.set('lon', lon) wpt_name = SubElement(wpt, 'name') wpt_name.text = u'%s' % (dt.isoformat()[:19]+'Z') wpt_desc = SubElement(wpt, 'desc') if desc is not None: wpt_desc.text = u'%s' % (desc) else: wpt_desc.text = u'(%s) %s' % (weather, revgeo) waypoints.append(wpt) for waypoint in waypoints: root.append(waypoint) if not xcode: root.append(track) for trackpoint in trackpoints: segment.append(trackpoint) try: distance = haversine(lat1, lon1, lat2, lon2) track_desc.text = "Distance: %.2f" % distance except: track_desc.text = "Distance unknown" print prettify(root)
# else: # bb_AS_link.set('latency', bb_link_lat) if visited == 0: # Creating routes to connect to serverAS serverAS_route = ET.SubElement(P, 'ASroute') serverAS_route.set('src', serverAS_prefix + upper_as_num) serverAS_route.set('dst', exitAS_prefix + upper_as_num) serverAS_route.set('gw_src', server_router_prefix + upper_as_num) serverAS_route.set('gw_dst', router_prefix + upper_as_num) serverAS_route.set('symmetrical', "YES") serverAS_route_link_ctn = ET.SubElement(serverAS_route, 'link_ctn') serverAS_route_link_ctn.set('id', serverAS_link_prefix + upper_as_num) # Creating routes to connect to sub ASes for i in range(branchNum): as_num = upper_as_num + ids[i] bb_AS_route = ET.SubElement(P, 'ASroute') bb_AS_route.set('src', AS_prefix + as_num) bb_AS_route.set('dst', exitAS_prefix + upper_as_num) bb_AS_route.set('gw_src', router_prefix + as_num) bb_AS_route.set('gw_dst', router_prefix + upper_as_num) bb_AS_route.set('symmetrical', "YES") bb_AS_route_link_ctn = ET.SubElement(bb_AS_route, 'link_ctn') bb_AS_route_link_ctn.set('id', bb_link_prefix + as_num) createAS(p - 1, d, 0, Root_AS) print prettify(platform)
# rootServers = getRootServers(client, candidateServers) # print rootServers # for rootSrv in rootServers: # candidateServers.remove(rootSrv) # argu = ET.SubElement(clientProc, 'argument') # argu.set('value', rootSrv) sortedCandidates = sortCandidate(client, candidateServers) sortedServers = [] for k, v in sortedCandidates: # print k sortedServers.append(k) # sortedServers = sortedCandidates.keys() leftNum = candidateNum availNum = len(candidateServers) if leftNum < availNum: for i in range(leftNum): selectedServer = sortedServers[i] print i, " selected Server for client ", client, " is ", selectedServer argu = ET.SubElement(clientProc, 'argument') argu.set('value', selectedServer) else: for candidate in candidateServers: argu = ET.SubElement(clientProc, 'argument') argu.set('value', candidate) # print ET.tostring(comment) # print prettify(platform) deploymentFile.write(prettify(platform))
#!/usr/bin/env python # -*- coding: utf-8 -*- """Creating XML documents with lists of nodes """ from xml.etree.ElementTree import Element, SubElement, tostring, XML from ElementTree_pretty import prettify top = Element('top') parent = SubElement(top, 'parent') children = XML( '<root><child num="0" /><child num="1" /><child num="2" /></root>' ) parent.extend(children) print prettify(top)
def writeToFolder(self, foldername): self.updatePoly() headerFolder = os.path.abspath(foldername) if not os.path.exists(headerFolder): os.makedirs(headerFolder) outputUp = headerFolder + '/up.vtp' outputDown = headerFolder + '/down.vtp' outputCrest = headerFolder + '/crest.vtp' writer = vtk.vtkXMLPolyDataWriter() writer.SetDataModeToAscii() #------------------------------------------------- # Write header.xml #------------------------------------------------- root = Element('s-rep') nRowsXMLElement = SubElement(root, 'nRows') nRowsXMLElement.text = str(self.__nRows) nColsXMLElement = SubElement(root, 'nCols') nColsXMLElement.text = str(self.__nCols) meshTypeXMLElement = SubElement(root, 'meshType') meshTypeXMLElement.text = 'Quad' colorXMLElement = SubElement(root, 'color') redXMLElement = SubElement(colorXMLElement, 'red') redXMLElement.text = str(0) greenXMLElement = SubElement(colorXMLElement, 'green') greenXMLElement.text = str(0.5) blueXMLElement = SubElement(colorXMLElement, 'blue') blueXMLElement.text = str(0) isMeanFlagXMLElement = SubElement(root, 'isMean') isMeanFlagXMLElement.text = 'False' meanStatPathXMLElement = SubElement(root, 'meanStatPath') meanStatPathXMLElement.text = '' upSpokeXMLElement = SubElement(root, 'upSpoke') upSpokeXMLElement.text = os.path.join(outputUp) downSpokeXMLElement = SubElement(root, 'downSpoke') downSpokeXMLElement.text = os.path.join(outputDown) crestSpokeXMLElement = SubElement(root, 'crestSpoke') crestSpokeXMLElement.text = os.path.join(outputCrest) file_handle = open(foldername + '/header.xml', 'w') file_handle.write(prettify(root)) file_handle.close() #------------------------------------------ # write children #------------------------------------------ writer.SetFileName(outputUp) writer.SetInputData(self.__vtkUpPoly) writer.Update() writer.SetFileName(outputDown) writer.SetInputData(self.__vtkDownPoly) writer.Update() writer.SetFileName(outputCrest) writer.SetInputData(self.__vtkCrestPoly) writer.Update()
def html_prepare(lis_in): m = 33 n = 33 length = lis_in[0].split("\t")[5] ID = lis_in[0].split("\t")[0] tick = str(round(float(length)/50)) tick2 = str(round(float(length)/12)) result = open(os.path.join(result_dir, ID + ".html"), "w") root = Element("html") root.set('version', '1.0') head = SubElement(root, 'head') title = SubElement(head, 'script', attrib= {"src":"js/angularplasmid.complete.min.js"}) title.text = " " # title.text = " src='js/angularplasmid.complete.min.js'" body = SubElement(root, 'body') style = SubElement(body, 'style') ti_style = SubElement(style, "setting") ti_style.text = " body {font-family: 'Lato';font-weight:400;}" \ ".boundary {stroke-dasharray:2,2;stroke-width:2px}" \ ".mdlabel {font-size:14px}" \ ".smlabel {font-size:8px}" \ ".white {fill:#fff}" \ ".red {fill:rgb(192,64,64)}" \ ".purple {fill:rgb(192,64,192)}" \ ".blue {fill:rgb(64,192,192)}" \ ".green {fill:rgb(64,192,64)}" \ ".labelline {stroke:#333;stroke-dasharray:2,2;stroke-width:2px;}" \ ".gold {fill:rgb(192,128,64)}" \ "" plasmid = SubElement(body, 'plasmid', attrib={"sequencelength": length, "plasmidheight": '700', "plasmidwidth":'700'}) plasmidtrack = SubElement(plasmid, 'plasmidtrack', attrib={"trackstyle":"fill:#ccc", "width":"5", "radius":"150"}) plasmidtrack.text = " " plasmidtrack2 = SubElement(plasmid, 'plasmidtrack', attrib={"trackstyle":"fill:rgba(225,225,225,0.5)","radius":"140"}) tracklabel = SubElement(plasmidtrack2, "tracklabel", attrib={"text":ID, "labelstyle":"font-size:20px;font-weight:400"}) tracklabel.text = " " tracklabel = SubElement(plasmidtrack2, "tracklabel", attrib={"text":length + " bp", "labelstyle":"ffont-size:10px", "vadjust":"20"}) tracklabel.text = " " trackscale = SubElement(plasmidtrack2, "trackscale", attrib={"interval":tick, "style":"stroke:#999", "ticksize":"3"}) trackscale.text = " " trackscale = SubElement(plasmidtrack2, "trackscale", attrib={"interval":tick, "style":"stroke:#999","direction": "in", "ticksize":"3"}) trackscale.text = " " trackscale = SubElement(plasmidtrack2, "trackscale", attrib={"interval":tick2, "style":"stroke:#f00", "direction":"in", "showlabels":"1", "labelstyle":"fill:#999;stroke:none;text-anchor:middle;alignment-baseline:middle;font-size:10px"}) trackscale.text = " " for i in lis_in: if "MOB" in i: mob_type = str(i).split("\t")[1] start = str(i).split("\t")[3].split("-")[0] end = str(i).split("\t")[3].split("-")[1] if str(i).split("\t")[4] == str(1): arrow_s = str(-2) arrow_e = str(2) else: arrow_s = str(2) arrow_e = str(-2) trackmarker = SubElement(plasmidtrack2, "trackmarker", attrib={"start":start, "end":end,"markerstyle":"fill:rgba(85,0,170,0.9)", "arrowendlength":arrow_e, "arrowstartlength":arrow_s}) markerlabel = SubElement(trackmarker, "markerlabel", attrib={"type":"path", "class":"mdlabel purple","valign":"outer","vadjust":"23","text":mob_type}) markerlabel.text = " " trackmarker = SubElement(plasmidtrack2, "trackmarker", attrib={"start":start, "end":end,"markerstyle":"fill:rgba(238,221,255,0.6)", "wadjust":"-5", "vadjust":"25"}) trackmarker.text = " " if "ATPase" in i: start = str(i).split("\t")[3].split("-")[0] end = str(i).split("\t")[3].split("-")[1] if str(i).split("\t")[4] == str(1): arrow_s = str(-2) arrow_e = str(2) else: arrow_s = str(2) arrow_e = str(-2) trackmarker = SubElement(plasmidtrack2, "trackmarker", attrib={"start":start, "end":end,"markerstyle":"fill:rgba(0,85,170,0.9)", "arrowendlength":arrow_e, "arrowstartlength":arrow_s}) markerlabel = SubElement(trackmarker, "markerlabel", attrib={"type":"path", "class":"mdlabel blue","valign":"outer","vadjust":"23","text":"ATPase"}) markerlabel.text = " " trackmarker = SubElement(plasmidtrack2, "trackmarker", attrib={"start":start, "end":end,"markerstyle":"fill:rgba(221,238,255,0.6)", "wadjust":"-5", "vadjust":"25"}) trackmarker.text = " " if "T4CP" in i: start = str(i).split("\t")[3].split("-")[0] end = str(i).split("\t")[3].split("-")[1] if str(i).split("\t")[4] == str(1): arrow_s = str(-2) arrow_e = str(2) else: arrow_s = str(2) arrow_e = str(-2) trackmarker = SubElement(plasmidtrack2, "trackmarker", attrib={"start":start, "end":end,"markerstyle":"fill:rgba(170,85,0,0.9)", "arrowendlength":arrow_e, "arrowstartlength":arrow_s}) markerlabel = SubElement(trackmarker, "markerlabel", attrib={"type":"path", "class":"mdlabel gold", "valign":"outer","vadjust":"23", "text":"T4CP"}) markerlabel.text = " " trackmarker = SubElement(plasmidtrack2, "trackmarker", attrib={"start":start, "end":end,"markerstyle":"fill:rgba(255,238,221,0.6)", "wadjust":"-5", "vadjust":"25"}) trackmarker.text = " " if "MPFG" not in i and "MPFI" not in i and "MPFT" not in i and "MPFF" not in i and "MOB" not in i: i = i + "\t" + str(n) n +=15 start = str(i).split("\t")[3].split("-")[0] end = str(i).split("\t")[3].split("-")[1] des = str(i).split("\t")[1].split("__")[1] adjARG = str(i).split("\t")[6] if str(i).split("\t")[4] == str(1): arrow_s = str(-2) arrow_e = str(2) else: arrow_s = str(2) arrow_e = str(-2) trackmarker = SubElement(plasmidtrack2, "trackmarker", attrib={"start":start, "end":end,"markerstyle":"fill:rgba(170,0,85,0.9)", "arrowendlength":arrow_e, "arrowstartlength":arrow_s}) markerlabel = SubElement(trackmarker, "markerlabel", attrib={"type":"path", "class":"mdlabel red", "valign":"outer","vadjust":adjARG,"text":des,"showline":"1","lineclass":"labelline"}) markerlabel.text = " " trackmarker = SubElement(plasmidtrack2, "trackmarker", attrib={"start":start, "end":end,"markerstyle":"fill:rgba(255,221,238,0.6)", "wadjust":"-5", "vadjust":"25"}) trackmarker.text = " " if "virB" in i or "traC" in i or "traE" in i or "traH" in i or "traK" in i or "MPFG_41" in i or "MPFG_44" in i or "MPFG_51" in i or "MPFG_52" in i\ or "traL" in i or "traN" in i or "traU" in i or "traV" in i or "traW" in i or "traI" in i or "traQ" in i or "traM" in i or "traP" in i\ or "traR" in i or "traY" in i: i = i + "\t" + str(m) m +=15 start = str(i).split("\t")[3].split("-")[0] end = str(i).split("\t")[3].split("-")[1] des = str(i).split("\t")[1].rsplit("_",1)[1] adj = str(i).split("\t")[6] if str(i).split("\t")[4] == str(1): arrow_s = str(-2) arrow_e = str(2) else: arrow_s = str(2) arrow_e = str(-2) trackmarker = SubElement(plasmidtrack2, "trackmarker", attrib={"start":start, "end":end,"markerstyle":"fill:rgba(85,170,0,0.9)", "arrowendlength":arrow_e, "arrowstartlength":arrow_s}) markerlabel = SubElement(trackmarker, "markerlabel", attrib={"type":"path", "class":"mdlabel green","valign":"outer","vadjust":adj, "text":des, "showline":"1","lineclass":"labelline"}) markerlabel.text = " " trackmarker = SubElement(plasmidtrack2, "trackmarker",attrib={"start": start, "end": end, "markerstyle": "fill:rgba(238,255,221,0.6)","wadjust": "-5", "vadjust": "25"}) trackmarker.text = " " result.write(prettify(root))
def network_config(): print "Processing the submitted configurations for Network" # flag to print debug statements, enable only during development or during debugging. debug = 0 # a top element for the config file - to hold a brief description top = Element('top') comment = Comment('Config File for Network') top.append(comment) # Checking for null values # - if not null then extract value and add it to xml tree if request.form['db_name']: db_name = request.form['db_name'] if debug: print db_name child = SubElement(top, 'Database_Name') child.text = db_name if request.form.get('person'): person = request.form['person'] if debug: print person child = SubElement(top, 'Person') child.text = person if request.form.get('base_entity'): base_entity = request.form['base_entity'] if debug: print base_entity child = SubElement(top, 'Base_Entity') child.text = base_entity if request.form.get('card'): card = request.form['card'] if debug: print card child = SubElement(top, 'Card') child.text = card if request.form['num_users']: num_users = request.form['num_users'] if debug: print num_users child = SubElement(top, 'Num_of_users') child.text = child if request.form['network_type'] != "no": network_type = request.form['network_type'] if debug: print network_type child = SubElement(top, 'Network_Topology') child.text = network_type if request.form['num_friends']: num_friends = request.form['num_friends'] if debug: print num_friends child = SubElement(top, 'Num_of_friends') child.text = num_friends recalibrate = request.form['recalibrate'] if debug: print recalibrate child = SubElement(top, 'Recalibrate_Network') child.text = recalibrate if request.form['single_user']: single_user = request.form['single_user'] if debug: print single_user child = SubElement(top, 'Single_User') child.text = single_user if request.form.get('clear_network'): clear_network = request.form['clear_network'] if debug: print clear_network child = SubElement(top, 'Clear_Network') child.text = clear_network if request.method == 'POST': infile = request.files['custom_friends'] if debug: print infile if infile and allowed_file(infile.filename): filename = secure_filename(infile.filename) infile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) child = SubElement(top, 'File_for_custom_friends') child.text = os.path.join(app.config['UPLOAD_FOLDER'], filename) # Prettify the xml before writing to file output_xml = prettify(top) print "Saving the config file for Network" # save in config_data file. # make sure to change the path to store the config file here outfile = open('config_data/network_config.xml',"w") outfile.write(output_xml) outfile.close() return "Success! Network configurations saved"
# tree.append(('Root', node)) # tree.append(get_nodes(node)) links.append(('Root', node)) tree = get_nodes('Root') #xmlTree = [ # Element('page', id=str(node)) ## get_nodes(node) # ] #print json.dumps(tree, indent=4) #exit() # XML # top = ET.Element("root") # top.extend(get_nodes('Root')) #top.extend(tree) top = Element('page') top.extend(get_nodes('Root')) print prettify(top).encode('utf-8') # print top xml = ET.fromstring(ET.tostring(top)) myxml = xml.findall("./pages/page/pages/page") # root = myxml.getroot() # print ET.tostring(root)
#!/usr/bin/env python3 # encoding: utf-8 # # Copyright (c) 2010 Doug Hellmann. All rights reserved. # """Creating XML documents with lists of nodes """ #end_pymotw_header from xml.etree.ElementTree import ( Element, SubElement, tostring, XML, ) from ElementTree_pretty import prettify top = Element('top') parent = SubElement(top, 'parent') children = XML('<root><child num="0" /><child num="1" />' '<child num="2" /></root>') parent.extend(children) print(prettify(top))
# 0.999847695156391,\ # 0.999961923064171,\ # 1.0}") # Reflection Tally parameter_2 = ET.SubElement(root, "ParameterList", name="Reflection Current") ET.SubElement(parameter_2, "Parameter", name="Id", type="unsigned int", value="2") ET.SubElement(parameter_2, "Parameter", name="Type", type="string", value="Surface Current") ET.SubElement(parameter_2, "Parameter", name="Particle Type", type="string", value="Electron") ET.SubElement(parameter_2, "Parameter", name="Surfaces", type="Array", value="{46}") sub_list_2 = ET.SubElement(parameter_2, "ParameterList", name="Bins") ET.SubElement(sub_list_2, "Parameter", name="Cosine Bins", type="Array", value="{-1.0, -0.999999, 1.0}") # Reflection Tally parameter_3 = ET.SubElement(root, "ParameterList", name="Cell Track Length Flux Estimator") ET.SubElement(parameter_3, "Parameter", name="Id", type="unsigned int", value="3") ET.SubElement(parameter_3, "Parameter", name="Type", type="string", value="Cell Track-Length Flux") ET.SubElement(parameter_3, "Parameter", name="Particle Type", type="string", value="Electron") ET.SubElement(parameter_3, "Parameter", name="Cells", type="Array", value="{7}") sub_list_3 = ET.SubElement(parameter_3, "ParameterList", name="Bins") ET.SubElement(sub_list_3, "Parameter", name="Energy Bins", type="Array", value="{1.5e-5, 99l, 15.7") prettify(root,"est.xml")
def parse_file_info(self): """ :return: """ if not self.lines: print('Please read file first\n') return f_ignore = False method_type = 'private' f_method = False f_struct = False #init unparsed_index = 0 unparsed_text_id = 0 nest_layer = [] # save current layer nest_layer_num = 0 # count nest layer num saved_enum_name = '' content = Element('content') current_group = content nest_layer.append(content) nest_layer_num = 1 #pretreat texts new_lines = [] for index, line in enumerate(self.lines): line = line.replace('{', '\n{\n') #make sure '{' and '}' be splited line = line.replace('(', ' ( ') line = line.replace(')', ' ) ') # line = line.replace('}','\n}\n') line = line.lstrip() #delete former blank if line.startswith( '__CODEGEN_BITFIELD'): #in case unfinished definition new_lines[-1] = new_lines[-1].strip('\n') + ' ' + line else: line = line.split('\n') new_lines.extend([x.strip() for x in line if x]) #filter blank in the list # print(new_lines[373]) for index, line_clr in enumerate(new_lines): # debug part #print(index) #print('----------------------------------\n') #print(prettify(content)) #------------------------------------------------------- #parse comment part, which can be ignored(cleared) if f_ignore: idx = line_clr.find('*/') if idx == -1: continue else: #comment end f_ignore = False line_clr = line_clr[idx + 2:] if line_clr.startswith('/*'): #comment start f_ignore = True continue # continue may ignore the content and cause some problem if line_clr.find('//') != -1: idx = line_clr.find('//') line_clr = line_clr[:idx] if not line_clr: continue #clear comment part, ignore blank line #-------------------------------------------------------- #------------------------------------------------------ #parse pre-defined parts if line_clr.startswith('#include'): self.includes.add(line_clr[10:-1]) continue #Jyq ##J elif line_clr.startswith('#'): self.elpredef.add(line_clr[1:]) continue #----------------------------------------------------- #----------------------------------------------------- # save as xml data, easy to parse nested structures #if (current_group is None # or group_name != current_group.text): # # Start a new group # current_group = SubElement( # content, 'outline', # {'text': group_name}, #) #--------------------------------------------------- #-------------------------------------------- # manage nest layer if line_clr.find('{') != -1: nest_layer.append( current_group ) #enter child layer, problem occurs when unparse function nest_layer_num += 1 if index - unparsed_index == 2: # parse {} in one line but {} are splited before unparsed_index += 1 #idx = line_clr.find('{') #if line_clr[idx+1]: # line_clr = line_clr[idx+1:] #else: continue #-------------------------------------------------------- #------------------------------------------------------------- #parse "mhw_sfc_g10_X::SFC_AVS_STATE_CMD::SFC_AVS_STATE_CMD()" # :: is called scope resolution operator #mylass::mystructcmd::constructor pattern = re.search('(.*)::(.*_CMD)::(.*_CMD)()', line_clr) if pattern: #myclass = SubElement(current_group, 'class', {'name' : pattern.group(1)}) #mystructcmd = SubElement(myclass, 'struct', {'name' : pattern.group(2)}) constructor = SubElement( current_group, 'constructor', { 'name': pattern.group(3), 'class': pattern.group(1), 'struct': pattern.group(2) }) current_group = constructor continue #------------------------------------------------------------- #------------------------------------------------------------- #parse dword field initiate value #eg. "DW0.Value = 0;" # DW0.DwordLength = GetOpLength(dwSize); # DW0.Subopcodeb = SUBOPCODEB_SFCAVSSTATE; # DW2_3.Value[0] = DW2_3.Value[1] = 0; #pattern = re.search('(DW.*)[.](.*)=(.*);', line_clr) pattern = re.findall( '(DW[0-9]+_?[0-9]*)[.]([a-zA-Z0-9\[\].]+)\s*=', line_clr) # dw_group = = [('DW22', 'Value[0]'), ('DW2_3', 'Value[1]')] if pattern: value = line_clr.split('=')[-1].strip().strip(';').strip() for dw, fieldname in pattern: if re.search('([a-zA-Z0-9]+)\[([0-9]+)\]', fieldname): dword = SubElement(current_group, dw, { 'arrayname': fieldname, 'value': value }) else: dword = SubElement(current_group, dw, {fieldname: value}) continue #------------------------------------------------------------- #-------------------------------------------- #parse datastructure = {'class', 'struct', 'union', 'enum' , 'namespace' } if any([line_clr.startswith(item) for item in self.datastructure]): self.structure_type, self.structure_name, self.super_structure_type, self.super_structure_name = self.get_datastructure( line_clr) new_datastruct_group = SubElement(current_group, self.structure_type) current_group = new_datastruct_group if self.structure_name: current_group.set('name', self.structure_name) if self.super_structure_type: current_group.set('super_structure_type', self.super_structure_type) current_group.set('super_structure_name', self.super_structure_name) continue #------------------------------------------------------------- #------------------------------------------------------------- #parse member_accessors = {'public:', 'protected:', 'private:' } if line_clr in self.member_accessors: member_accessor = line_clr.strip(':') new_group = SubElement(current_group, member_accessor) current_group = new_group nest_layer.append(current_group) nest_layer_num += 1 continue #---------------------------------------------------- #-------------------------------------------- #parse basic_type = {'int', 'bool', 'dword', 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t', 'char'} if any([line_clr.startswith(item) for item in self.basic_type]): self.type, self.basic_name, self.arraysize, self.address, self.prefix, self.value, self.para_name, self.para_type = self.parse_basictype( line_clr) if self.basic_name: new_basic_group = SubElement(current_group, self.type, name=self.basic_name) if self.address: new_basic_group.set('bitfield', self.address) if self.arraysize: new_basic_group.set('arraysize', self.arraysize) if self.para_name: ### Problems!!!! for i, para_name in enumerate(self.para_name): new_func_group = SubElement( current_group, 'FUNCTION', { 'para_name': para_name, 'para_type': self.para_type[i] }) current_group = new_func_group continue #parse datatype above, but with prefix #e.g.: 'static const size_t dwSize = 1;' if any([line_clr.startswith(item) for item in self.prefixset]) and line_clr.find('=') != -1: self.type, self.basic_name, self.arraysize, self.address, self.prefix, self.value, self.para_name, self.para_type = self.parse_basictype( line_clr) #exclude exceptions if self.type not in self.basic_type: break new_basic_group = SubElement(current_group, self.type, name=self.basic_name) if self.address: new_basic_group.set('address', self.address) if self.prefix: new_basic_group.set('prefix', self.prefix) if self.value: new_basic_group.set('value', self.value) continue #------------------------------------------------------------- #------------------------------------------------------------ #pase member inside enum{}, always set value? #suppose set value #e.g. 'FORCEINTRA_ENABLE = 1,' if current_group.tag == 'enum': if line_clr.find('=') != -1: idx = line_clr.find('=') name = line_clr[:idx].strip() value = line_clr[idx + 1:line_clr.find(',')].strip() if current_group.attrib['name'] == saved_enum_name: text_id += 1 else: text_id = 0 enum_member_group = SubElement(current_group, 'text', id=str(text_id)) enum_member_group.set('name', name) enum_member_group.set('value', value) saved_enum_name = current_group.attrib['name'] continue #------------------------------------------------------------ #------------------------------------------------------------ #pase reference member inside struct xxx_CMD{yyy_CMD zzz;} #and constructor xxx_CMD{xxx_CMD();} #only those endwith '_CMD' #e.g. 'VDENC_64B_Aligned_Lower_Address_CMD LowerAddress # 'HUC_VIRTUAL_ADDR_REGION_CMD HucVirtualAddressRegion[16]; ' if line_clr.find('_CMD') != -1: if (current_group.tag == 'struct' and 'name' in current_group.attrib and current_group.attrib['name'].endswith('_CMD') ) or current_group.tag == 'union': if 'name' in current_group.attrib: #1: constructor xxx_CMD{xxx_CMD();} constructor = current_group.attrib['name'] if line_clr.startswith( constructor ) and '(' in line_clr and ')' in line_clr: constructor_group = SubElement( current_group, 'constructor', {'name': constructor}) idx1 = '(' idx2 = ')' line_clr1 = line_clr[line_clr.find(idx1) + 1:line_clr.find(idx2)].strip( ) if line_clr1: constructor_group.set('text', line_clr1) continue #2: otherstruct yyy_CMD zzz; #3: inside union yyy_CMD zzz; # may have exceptions line_clr1 = line_clr.strip().strip(';').strip() item_list = line_clr1.split() otherCMD = item_list[0] if otherCMD.endswith('_CMD'): name = item_list[1] otherCMD_group = SubElement(current_group, 'otherCMD') if re.search('\[\d+\]', name): arraysize = re.search( '\[\d+\]', name)[0].strip('[').strip(']') otherCMD_group.set('arraysize', arraysize) otherCMD_group.set('otherCMD', otherCMD) otherCMD_group.set('name', name) continue #------------------------------------------------------------ #------------------------------------------------------------ # parse 'return xxx;}' and 'return xxx;' # error when former function unparsed if line_clr.startswith('return'): return_value = line_clr.strip('return').strip().strip( ';').strip() return_group = SubElement(current_group, 'return') return_group.set('value', return_value) #------------------------------------------------------------ #------------------------------------------------------------ # manage nest layer, position fixed in the end part if line_clr.find('}') != -1: nest_layer.pop() #exit current layer, return to parent nest_layer_num -= 1 if line_clr.find(';') != -1: #current_group = nest_layer[-1] idx1 = '}' idx2 = ';' line_clr1 = line_clr[line_clr.find(idx1) + 1:line_clr.find(idx2)].strip() # if'};' simply exit current layer, look like struct definition finished if line_clr1: # parse '} DW0;', post-positioned name text = line_clr1 current_group.set('name', text) # if'xxx;}' xxx maybe parsed above, maybe 'return __CODEGEN_OP_LENGTH(uiLength); }' # if unparsed, will lose xxx; line_clr2 = line_clr[:line_clr.find(idx2)].strip() if nest_layer: current_group = nest_layer[-1] continue #------------------------------------------------------------- #------------------------------------------------------------- #consecutive unparsed part save as text #if index-unparsed_index != 1 : # unparsed_text = '' #print(line_clr) #leave function(xx){return xx ;} unparsed unparsed_text = line_clr unparsed_text_id += 1 unparsed_text_group = SubElement(current_group, 'unparsedtext', id=str(unparsed_text_id)) unparsed_text_group.text = unparsed_text #test, see each update xml #print(prettify(content)) #------------------------------------------- #print(prettify(content)) return prettify(content)
type="Array", value=bins) # Particle Tracker (if asked for) if user_args.p == "true": tally_number = tally_number + 1 tally = "Particle Tracker" parameter_4 = ET.SubElement(root, "ParameterList", name="Particle Tracker 1") ET.SubElement(parameter_4, "Parameter", name="Id", type="unsigned int", value=str(tally_number)) ET.SubElement(parameter_4, "Parameter", name="Type", type="string", value=tally) name = name_base + ".xml" i = 1 while os.path.isfile(name): name = name_base + "_" + str(i) + ".xml" i = i + 1 prettify(root, name) print name
def main(): args = getArgs() output = os.path.abspath(args.output) edlInput = args.input if args.format == 'ccc': if output[-3:] != 'ccc': raise ValueError( 'The Output(-o) must be a file that ends in ".ccc" when using the format(-f) "ccc".' ) output_path = os.path.split(output)[0] if not os.path.isdir(output_path): os.mkdir(output_path) else: if os.path.splitext(output)[1]: raise ValueError( 'The Output(-o) must be a folder when using the format(-f) "cc" or "cdl".' ) try: os.mkdir(output) except OSError as e: if e.errno == errno.EEXIST: pass else: raise cdl1re = re.compile( r"\*\s?ASC[_]SOP\s+[(]\s?(?P<sR>[-]?\d+[.]\d{4,6})\s+(?P<sG>[-]?\d+[.]\d{4,6})\s+(?P<sB>[-]?\d+[.]\d{4,6})\s?[)]\s?[(]\s?(?P<oR>[-]?\d+[.]\d{4,6})\s+(?P<oG>[-]?\d+[.]\d{4,6})\s+(?P<oB>[-]?\d+[.]\d{4,6})\s?[)]\s?[(]\s?(?P<pR>[-]?\d+[.]\d{4,6})\s+(?P<pG>[-]?\d+[.]\d{4,6})\s+(?P<pB>[-]?\d+[.]\d{4,6})\s?[)]" ) cdl2re = re.compile(r"\*\s?ASC[_]SAT\s+(?P<sat>\d+([.]\d{4,6})?)") CDLevent = False thisCDL = None IDs = [] CCC = [] if args.event == 'clip': camre = re.compile( r"\*\s?FROM\sCLIP\sNAME:\s+.*(?P<name>[A-Z][0-9]{3}[_]?C[0-9]{3})") camre0 = re.compile(r"\*\sFROM\sCLIP\sNAME:\s+(?P<name>.{63})") camre1 = re.compile(r"[*]\s(?P<name>.*)") #Greedier FROM CLIP NAME Regex camre3 = re.compile(r"\*\s?FROM\sCLIP\sNAME:\s+(?P<name>[A-Z0-9_\-]+)") tapere = re.compile( r"\*\sFROM\sCLIP\sNAME:\s+(?P<name>[A-Za-z0-9-_,.]|\s{8,32})") edlLines = edlInput.readlines() lenEdlLines = len(edlLines) for n in range(lenEdlLines): line = edlLines[n].strip() # Skip all lines that aren't EDL Comments/Notes if line[0] != '*': continue if camre.match(line): CDLevent, L = True, camre.match(line) if thisCDL: writeCDL(CCC, IDs, tapename, thisCDL, thisSAT) thisCDL, thisSAT = None, 0 tapename = L.group("name") if tapename in IDs: tapename, CDLevent = None, False elif camre0.match(line) and n < lenEdlLines - 1 and camre1.match( edlLines[n + 1]): n += 1 line = line + camre1.match(edlLines[n]).group("name") L = camre.match(line) if not L: writeCDL(CCC, IDs, tapename, thisCDL, thisSAT) thisCDL, thisSAT = None, 0 else: CDLevent = True tapename = L.group("name") if tapename in IDs: tapename, CDLevent = None, False if thisCDL: thisCDL, thisSAT = None, 0 elif tapere.match(line): CDLevent, L = True, tapere.match(line) if thisCDL: writeCDL(CCC, IDs, tapename, thisCDL, thisSAT) thisCDL, thisSAT = None, 0 tapename = L.group("name") if tapename in IDs: tapename, CDLevent = None, False elif camre3.match(line): CDLevent, L = True, camre3.match(line) if thisCDL: writeCDL(CCC, IDs, tapename, thisCDL, thisSAT) thisCDL, thisSAT = None, 0 tapename = L.group("name") if tapename in IDs: tapename, CDLevent = None, False elif CDLevent and cdl1re.match(line): L = cdl1re.match(line) thisCDL = cdl1Parse(L) thisSAT = 0 elif CDLevent and thisCDL and cdl2re.match(line): L = cdl2re.match(line) thisSAT = float(L.group("sat")) writeCDL(CCC, IDs, tapename, thisCDL, thisSAT) tapename, CDLevent, thisCDL, thisSAT = None, False, None, 0 else: #Find Locator locRE = re.compile( r'\*\s?LOC:\s+\d\d:\d\d:\d\d:\d\d\s+\w*\s+(?P<name>[\w\-]+)') for line in edlInput.readlines(): line = line.strip() # Skip all lines that aren't EDL Comments/Notes if line[0] != '*': continue matchLoc = locRE.match(line) if matchLoc: CDLevent = True if thisCDL: writeCDL(CCC, IDs, tapename, thisCDL, thisSAT) thisCDL, thisSAT = None, 0 tapename = matchLoc.group('name') if tapename in IDs: tapename, CDLevent = None, False continue matchCdl1 = cdl1re.match(line) if CDLevent and matchCdl1: thisCDL = cdl1Parse(matchCdl1) thisSAT = 0 continue matchCdl2 = cdl2re.match(line) if CDLevent and matchCdl2: thisSAT = float(matchCdl2.group('sat')) writeCDL(CCC, IDs, tapename, thisCDL, thisSAT) tapename, CDLevent, thisCDL, thisSAT = None, False, None, 0 continue if thisCDL: writeCDL(CCC, IDs, tapename, thisCDL, thisSAT) tapename, CDLevent, thisCDL, thisSAT = None, False, None, 0 edlInput.close() if not CCC: print "No Color Decision(s) found in EDL file \"%s\". Quitting." % os.path.split( edlInput.name)[1] sys.exit(0) print " * %d Color Decision(s) found in EDL file \"%s\"." % ( len(CCC), os.path.split(edlInput.name)[1]) if args.format == 'ccc': root = Element('ColorCorrectionCollection', {'xmlns': 'urn:ASC:CDL:v1.01'}) for cc in CCC: appendCCXML(cc['id'], cc['slope'], cc['offset'], cc['power'], cc['SAT'], root) with open(output, 'w') as cccOut: cccOut.write(prettify(root)) print " * %d CDL(s) written in CCC file \"%s\"" % ( len(CCC), os.path.split(output)[1]) else: for cc in CCC: if args.format == 'cdl': root = Element('ColorDecisionList', {'xmlns': 'urn:ASC:CDL:v1.01'}) appendCCXML(cc['id'], cc['slope'], cc['offset'], cc['power'], cc['SAT'], root) else: root = appendCCXML(cc['id'], cc['slope'], cc['offset'], cc['power'], cc['SAT'], None) with open(os.path.join(output, "%s.%s" % (cc['id'], args.format)), 'w') as outputFile: outputFile.write(prettify(root)) print " * %d individual %s(s) written in folder \"%s\"." % ( len(CCC), args.format, output)
dm.text = generated_on body = SubElement(root, 'body') with open('podcasts.csv', 'rt') as f: current_group = None reader = csv.reader(f) for row in reader: group_name, podcast_name, xml_url, html_url = row if (current_group is None or group_name != current_group.text): # Start a new group current_group = SubElement( body, 'outline', {'text': group_name}, ) # Add this podcast to the group, # setting all its attributes at # once. podcast = SubElement( current_group, 'outline', { 'text': podcast_name, 'xmlUrl': xml_url, 'htmlUrl': html_url }, ) print(prettify(root))
def writeXML(xmlroot): xmltree = ET.ElementTree(xmlroot) if options.logfile: xmltree.write(options.logfile) else: print prettify(xmlroot)
#!/usr/bin/env python # -*- coding: utf-8 -*- """Creating XML documents with lists of nodes """ from xml.etree.ElementTree import Element, tostring from ElementTree_pretty import prettify top = Element('top') children = [Element('child', num=str(i)) for i in xrange(3)] top.extend(children) print prettify(top)
def ptfy(): file = open("salida.xml", "w") file.write(str((prettify(top)))) file.close()
dc = SubElement(head, 'dateCreated') dc.text = generated_on dm = SubElement(head, 'dateModified') dm.text = generated_on body = SubElement(root, 'body') with open('podcasts.csv', 'rt') as f: current_group = None reader = csv.reader(f) for row in reader: group_name, podcast_name, xml_url, html_url = row if (current_group is None or group_name != current_group.text): # Start a new group current_group = SubElement( body, 'outline', {'text': group_name}, ) # Add this podcast to the group, # setting all its attributes at # once. podcast = SubElement( current_group, 'outline', {'text': podcast_name, 'xmlUrl': xml_url, 'htmlUrl': html_url}, ) print(prettify(root))
test = makeDevice("4","1","9669","Power Meter - Tweet-a-Watt","485") test = makeDevice("5","1","10267","Natural Gas Sensor - Dining room","0") test = makeDevice("6","0","10258","unused","0") test = makeDevice("7","1","24660","Office Multi-sensor PCB1","0") test = makeDevice("8","1","25131","Bed room Multi-sensor PCB1","0") test = makeDevice("9","1","25133","Guest room Multi-sensor PCB1","0") test = makeDevice("10","1","25134","Living Room Multi-sensor PCB1","0") test = makeDevice("11","1","25135","Experimental solar power tracking","0") test = makeDevice("12","0","","Power Meter - Tweet-a-Watt","486") test = makeDevice("13","0","","router receiver","0") test = makeDevice("14","0","","Terence","0") test = makeDevice("15","0","29631","unused","0") test = makeDevice("16","1","","Garage Multi-sensor PCB1","0") test = makeDevice("17","0","","unused","0") test = makeDevice("18","0","","unused","0") test = makeDevice("19","0","","unknown","0") test = makeDevice("20","0","","Terence","0") test = makeDevice("21","0","","unknown","0") # rough_string = ElementTree.tostring(tinajaTop, 'utf-8') # reparsed = minidom.parseString(rough_string) # prettyXML = reparsed.toprettyxml(indent=" ") prettyXML = prettify(tinajaTop) writeconfig(prettyXML) # print prettify(tinajaTop) print prettyXML print "done... "
head = SubElement(root, 'head') title = SubElement(head, 'title') title.text = 'My Podcasts' dc = SubElement(head, 'dateCreated') dc.text = generated_on dm = SubElement(head, 'dateModified') dm.text = generated_on body = SubElement(root, 'body') with open('podcasts.csv', 'rt') as f: current_group = None reader = csv.reader(f) for row in reader: group_name, podcast_name, xml_url, html_url = row if current_group is None or group_name != current_group.text: # Start a new group current_group = SubElement(body, 'outline', {'text':group_name}) # Add this podcast to the group, # setting all its attributes at # once. podcast = SubElement(current_group, 'outline', {'text':podcast_name, 'xmlUrl':xml_url, 'htmlUrl':html_url, }) print prettify(root)
def write_bcell_xml(diffusibles, celltypes, myreactions, myforces, mydomain, mygridsolver, mysimulator, directory): # write the files for biocellion xml_file = open(directory+"/run_param.xml", 'w') #Biocellion required parameters bcell_num_baseline = mysimulator['numbersteps'] #Number of steps of the simulation bcell_nx = mydomain['agar_heigth']+mydomain['nx'] #size in x ( Num. of grid points bcell_ny = mydomain['ny'] bcell_nz = mydomain['nz'] bcell_partition_size = 32 # multiple of max(4,refine_ratio^(AMR_levels - 1)*2(minimum box size)) bcell_path = directory + "/output" bcell_interval = int( mysimulator['outputPeriod'] ) # output interval bcell_start_x = 0 # start position from which results will be printed bcell_start_y = 0 bcell_start_z = 0 bcell_size_x = mydomain['nx'] + mydomain['agar_heigth'] # size of the region for printing bcell_size_y = mydomain['ny'] bcell_size_z = mydomain['nz'] # Biocellion optional parameteres bcell_input_param = directory + "/cells.txt" bcell_verbosity = 1 # [0-5] bcell_num_threads = 8 bcell_num_node_groups = 1 bcell_num_nodes_per_group = 8 bcell_num_sockets_per_node = 2 bcell_max_load_imbalance = 1.2 bcell_super_x = 64 bcell_super_y = 64 bcell_super_z = 64 bcell_summary = 1 bcell_load_balance = 1200 bcell_regridding = 1200 bcell_checkpoint = 1200 bcell_refine_ratio = 2 bcell_fill_ratio = 0.5 # Write xml for Biocellion top = Element('biocellion') comment = Comment('Input parameters for Biocellion, generated by Python parcer ') top.append(comment) # Printing Required parameterss xml_required = SubElement(top, 'required' ) xml_required.append( Comment('Required Parameters for biocellion.') ) xml_time_step = SubElement(xml_required, 'time_step') xml_time_step.set('num_baseline', str(bcell_num_baseline) ) xml_domain = SubElement(xml_required, 'domain') xml_domain.set('x', str(bcell_nx) ) xml_domain.set('y', str(bcell_ny) ) xml_domain.set('z', str(bcell_nz) ) xml_init_data = SubElement(xml_required, 'init_data') xml_init_data.set('partition_size', str(bcell_partition_size) ) xml_init_data.set('src',"code") # currently no imput from binary xml_output = SubElement(xml_required, 'output ') xml_output.set('path',bcell_path) xml_output.set('interval', str(bcell_interval) ) xml_output.set('particle',"pvtp") xml_output.set('grid',"vtm") xml_output.set('start_x', str(bcell_start_x) ) xml_output.set('start_y', str(bcell_start_y) ) xml_output.set('start_z', str(bcell_start_z) ) xml_output.set('size_x', str(bcell_size_x) ) xml_output.set('size_y', str(bcell_size_y) ) xml_output.set('size_z', str(bcell_size_z) ) # Printing Required parameterss xml_optional = SubElement(top, 'optional') xml_optional.append( Comment('optional Parameters for biocellion.') ) xml_bioparm_model = SubElement(xml_optional, 'model') xml_bioparm_model.set('param',bcell_input_param) xml_bioparm_stdout = SubElement(xml_optional, 'stdout') xml_bioparm_stdout.set('verbosity' , str(bcell_verbosity) ) xml_bioparm_system = SubElement(xml_optional,'system') xml_bioparm_system.set('num_node_groups', str(bcell_num_node_groups) ) xml_bioparm_system.set('num_nodes_per_group', str(bcell_num_nodes_per_group) ) xml_bioparm_system.set('num_sockets_per_node', str(bcell_num_sockets_per_node) ) xml_bioparm_system.set('max_load_imbalance', str(bcell_max_load_imbalance) ) xml_bioparm_system.set('num_threads', str( bcell_num_threads ) ) xml_bioparm_super_partition = SubElement(xml_optional,'super_partition') xml_bioparm_super_partition.set('x', str(bcell_super_x) ) xml_bioparm_super_partition.set('y', str(bcell_super_y) ) xml_bioparm_super_partition.set('z', str(bcell_super_z) ) xml_interval = SubElement(xml_optional,'interval') xml_interval.set('summary', str(bcell_summary) ) xml_interval.set('load_balance', str(bcell_load_balance) ) xml_interval.set('regridding', str(bcell_regridding) ) xml_interval.set('checkpoint', str(bcell_checkpoint) ) xml_amr = SubElement(xml_optional,'amr') xml_amr.set('refine_ratio', str(bcell_refine_ratio) ) xml_amr.set('fill_ratio' , str(bcell_fill_ratio) ) xml_file.write( prettify(top) )
# ElementTree_extend_node.py from xml.etree.ElementTree import Element, SubElement, tostring, XML) from ElementTree_pretty import prettify top = Element('top') parent = SubElement(top, 'genitore') children = XML( '<root><figlio num="0" /><figlio num="1" />' '<figlio num="2" /></root>' ) parent.extend(children) print(prettify(top))
def info_display_config(): print "Processing the submitted configurations for Information Display" # flag to print debug statements, enable only during development or during debugging. debug = 0 # a top element for the config file - to hold a brief description top = Element('top') comment = Comment('Config File for Information Display') top.append(comment) if request.form['threshold_positive']: threshold_positive = request.form['threshold_positive'] if debug: print threshold_positive child = SubElement(top, 'Threshold_Positive') child.text = threshold_positive if request.form['threshold_negative']: threshold_negative = request.form['threshold_negative'] if debug: print threshold_negative child = SubElement(top, 'Threshold_Positive') child.text = threshold_negative if request.form['threshold_per_day']: threshold_per_day = request.form['threshold_per_day'] if debug: print threshold_per_day child = SubElement(top, 'Threshold_Per_Day') child.text = threshold_per_day if request.form['threshold_time']: threshold_time = request.form['threshold_time'] if debug: print threshold_time child = SubElement(top, 'Threshold_Time') child.text = threshold_time if request.form['threshold_hierarchy']: threshold_hierarchy = request.form['threshold_hierarchy'] if debug: print threshold_hierarchy child = SubElement(top, 'Threshold_Hierarchy') child.text = threshold_hierarchy if request.form['flickr_api']: flickr_api = request.form['flickr_api'] if debug: print threshold_hierarchy child = SubElement(top, 'Flickr_API_Key') child.text = flickr_api if request.method == 'POST': infile = request.files['positive_messages'] if debug: print infile if infile and allowed_file(infile.filename): filename = secure_filename(infile.filename) infile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) child = SubElement(top, 'File_for_custom_friends') child.text = os.path.join(app.config['UPLOAD_FOLDER'], filename) infile = request.files['negative_messages'] if debug: print infile if infile and allowed_file(infile.filename): filename = secure_filename(infile.filename) infile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) child = SubElement(top, 'File_for_custom_friends') child.text = os.path.join(app.config['UPLOAD_FOLDER'], filename) infile = request.files['neutral_messages'] if debug: print infile if infile and allowed_file(infile.filename): filename = secure_filename(infile.filename) infile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) child = SubElement(top, 'File_for_custom_friends') child.text = os.path.join(app.config['UPLOAD_FOLDER'], filename) infile = request.files['weekly_messages'] if debug: print infile if infile and allowed_file(infile.filename): filename = secure_filename(infile.filename) infile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) child = SubElement(top, 'File_for_custom_friends') child.text = os.path.join(app.config['UPLOAD_FOLDER'], filename) infile = request.files['monthly_messages'] if debug: print infile if infile and allowed_file(infile.filename): filename = secure_filename(infile.filename) infile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) child = SubElement(top, 'File_for_custom_friends') child.text = os.path.join(app.config['UPLOAD_FOLDER'], filename) infile = request.files['all_time_messages'] if debug: print infile if infile and allowed_file(infile.filename): filename = secure_filename(infile.filename) infile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) child = SubElement(top, 'File_for_custom_friends') child.text = os.path.join(app.config['UPLOAD_FOLDER'], filename) infile = request.files['spatial_stats_messages'] if debug: print infile if infile and allowed_file(infile.filename): filename = secure_filename(infile.filename) infile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) child = SubElement(top, 'File_for_custom_friends') child.text = os.path.join(app.config['UPLOAD_FOLDER'], filename) infile = request.files['network_stats_messages'] if debug: print infile if infile and allowed_file(infile.filename): filename = secure_filename(infile.filename) infile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) child = SubElement(top, 'File_for_custom_friends') child.text = os.path.join(app.config['UPLOAD_FOLDER'], filename) infile = request.files['messages_with_images'] if debug: print infile if infile and allowed_file(infile.filename): filename = secure_filename(infile.filename) infile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) child = SubElement(top, 'File_for_custom_friends') child.text = os.path.join(app.config['UPLOAD_FOLDER'], filename) infile = request.files['messages_with_tables'] if debug: print infile if infile and allowed_file(infile.filename): filename = secure_filename(infile.filename) infile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) child = SubElement(top, 'File_for_custom_friends') child.text = os.path.join(app.config['UPLOAD_FOLDER'], filename) # Prettify the xml before writing to file output_xml = prettify(top) print "Saving the config file for Information Display" # save in config_data file. # make sure to change the path to store the config data here outfile = open('config_data/info_display_config.xml',"w") outfile.write(output_xml) outfile.close() return "Success! Information Display configurations saved"
ET.SubElement(root, "Parameter", name="Facet Tolerance", type="double", value="1e-3") ET.SubElement(root, "Parameter", name="Use Fast Id Lookup", type="bool", value="True") ET.SubElement(root, "Parameter", name="Termination Cell Property", type="string", value="termination.cell") ET.SubElement(root, "Parameter", name="Estimator Property", type="string", value="estimator") ET.SubElement(root, "Parameter", name="Material Property", type="string", value="mat") ET.SubElement(root, "Parameter", name="Density Property", type="string", value="rho") elif geom_type == "ROOT" or geom_type == "root" or geom_type == "Root": root_file = "h_sphere.root" name=name+"_root" ET.SubElement(root, "Parameter", name="Handler", type="string", value="ROOT") ET.SubElement(root, "Parameter", name="Root File", type="string", value=root_file) ET.SubElement(root, "Parameter", name="Terminal Material Name", type="string", value="graveyard") ET.SubElement(root, "Parameter", name="Void Material Name", type="string", value="void") ET.SubElement(root, "Parameter", name="Material Property Name", type="string", value="mat") else: # Just assume DagMC sat_file = "h_sphere.sat" ET.SubElement(root, "Parameter", name="Handler", type="string", value="DagMC") ET.SubElement(root, "Parameter", name="CAD File", type="string", value=sat_file) ET.SubElement(root, "Parameter", name="Facet Tolerance", type="double", value="1e-3") ET.SubElement(root, "Parameter", name="Use Fast Id Lookup", type="bool", value="True") ET.SubElement(root, "Parameter", name="Termination Cell Property", type="string", value="termination.cell") ET.SubElement(root, "Parameter", name="Estimator Property", type="string", value="estimator") ET.SubElement(root, "Parameter", name="Material Property", type="string", value="mat") ET.SubElement(root, "Parameter", name="Density Property", type="string", value="rho") name =name+".xml" prettify(root,name) print name
def create_xml(self): return prettify(self.top)