def get_slices(self, xml_obj): slices = dict() idx = 0 for child in xml_obj: if child.tag == 'slices': slice = dict() for et in child: if et.tag == 'sliceStart' or et.tag == 'sliceEnd': if et.text is None: xmltree.dump(et) slice.update({et.tag: time_convert(et.text)}) else: slice.update({et.tag: et.text}) # append tracks information tracks = self._get_tracks(slice) slice.update({'tracks': tracks}) # append files information files = self._get_files(slice, mediaType='videoclip', is_utc=True) slice.update({'files': files}) slices.update({idx: slice}) idx += 1 return slices
def make_xml(self): root = ET.Element('root') for ei, e in enumerate(self.events): print(e) event = ET.SubElement(root, 'event') event.set('code', str(e)) event.set('index', str(ei)) for u in self.all[e]: print(u) unit = ET.SubElement(event, 'unit') unit.set('unit_code', str(u)) for c in self.all[e][u]: print(c) coord = ET.SubElement(unit, 'coord') coord.set('lng',str(c[0])) coord.set('lnt',str(c[1])) coord.set('time',str(c[2])) ET.dump(root)
def updateTextBoxSettings(self, settings, key, widget): """ Handler for updating the XJOBSettings object Parameters: settings -- a Settings object key -- a 2-tuple specifying the branch and the leaf to set widget -- a reference to the value-holding widget """ value = widget.GetValue() # test for mask matching try: key[1] in ("PageMask", "FileMask") and PageFileMask(value).result is None key[1] == "Volume" and VolumeMask(value).result is None bad = False except: bad = True # if the mask isn't worth the screen it was printed on, set colors if bad: print "BAD:", value widget.SetForegroundColor("orange red") # else play nice and let settings go through else: widget.SetForegroundColor("black") # call out to settings settings[key] = value if __debug__: print ET.dump(self.settings._settings) # redraw the widget widget.Refresh()
def _convert_row(doc_date, xml): """ Given a default date (for the whole document) and a (date, entry) row, return * a (partial) iso string for the date * the text for the entry """ ths = list(xml.iter('th')) tds = list(xml.iter('td')) if len(ths) < 1: date = None elif len(ths) > 1: ET.dump(xml) raise Exception("Did not expect more than one th node") else: th_text = _clean_date(ths[0].text or "") date = read_date(th_text, prefix=doc_date, fuzzy=True) # or doc_date columns = ths + tds text = "\n".join(_column_to_text(x) for x in columns) if text: return date or doc_date, text else: return None
def getHosts(): #pede lista de hosts root = ET.Element('p2pse') gethosts = ET.SubElement(root,'getHosts') arq = ET.ElementTree(root) ET.dump(root) arq.write('getHosts.xml')
def merge_results(xml_files): failures = 0 tests = 0 errors = 0 time = 0.0 suites = [] for file_name in xml_files: tree = ET.parse(file_name) test_suites = tree.getroot() test_suite = tree.findall('testsuite')[0]; failures += int(test_suite.attrib['failures']) tests += int(test_suite.attrib['tests']) errors += int(test_suite.attrib['errors']) time += float(test_suite.attrib['time']) suites.append(test_suite) new_root = ET.Element('testsuites') new_root.attrib['failures'] = '%s' % failures new_root.attrib['tests'] = '%s' % tests new_root.attrib['errors'] = '%s' % errors new_root.attrib['time'] = '%s' % time for suite in suites: new_root.append(suite) new_tree = ET.ElementTree(new_root) ET.dump(new_tree)
def create_workflow(self, experiment_id, project_id, pipeline, status): """Creates a workflow entry and returns the primary key of the inserted workflow""" workflow_str_xml = '<wrk:Workflow data_type="xnat:mrSessionData" xmlns:xsi="http://www.w3.org/2001/XMSchema-instance" ' workflow_str_xml += 'xmlns:wrk="http://nrg.wuslt.edu/workflow" />' workflow_data_element = ET.fromstring(workflow_str_xml) ET.register_namespace('wrk', 'http://nrg.wustl.edu/workflow') workflow_data_element.set('ID', experiment_id) workflow_data_element.set('ExternalID', project_id) workflow_data_element.set('status', status) workflow_data_element.set('pipeline_name', pipeline) time_now = time.localtime() xml_time = time.strftime('%Y-%m-%dT%H:%M:%S', time_now) pretty_time_now = time.strftime('%Y-%m-%dT%H-%M-%S', time_now) workflow_data_element.set('launch_time', xml_time) workflow_data_str = ET.tostring(workflow_data_element) if sys.platform != 'win32': workflow_write_str = '/tmp/Workflow_%s_%s.xml' % (experiment_id, pretty_time_now) with open(workflow_write_str, 'wb') as output_file_obj: output_file_obj.write(workflow_data_str) workflow_submit_str = '$PIPELINE_HOME/xnat-tools/XnatDataClient -s %s -m PUT -r "%s/REST/workflows?req_format=xml&inbody=true" -l %s' % (self._jsession_id, self._server, workflow_write_str) # nopep8 subprocess.call(workflow_submit_str, shell=True, stdout=open("/dev/null", "w")) workflow_id = self.get_queued_workflow_id_as_parameter(pipeline, experiment_id) return workflow_id else: ET.dump(workflow_data_element) return -1
def createReactionMap(filename,publication_id,model_id,reactionmap = None, debug = False): ''' Writes a reaction map to an .xml file ''' root = ET.Element('xml') publication = ET.SubElement(root,'publication',attrib = {'id':publication_id}) model = ET.SubElement(publication,'model',attrib={'id':model_id}) if debug == True: ET.dump(root) if reactionmap is not None: for linkdict in reactionmap: newlink = ET.SubElement(model,'link') for expreactiondict in linkdict['exprxns']: new_exprxn = ET.SubElement(newlink,'exprxn',attrib = {'id':expreactiondict['rxid'],'coef':str(expreactiondict['coef'])}) for modelreactiondict in linkdict['modrxns']: if 'coef' in modelreactiondict: new_modrxn = ET.SubElement(newlink,'modelrxn',attrib = {'id':modelreactiondict['rxid'],'coef':str(modelreactiondict['coef'])}) else: new_modrxn = ET.SubElement(newlink,'modelrxn',attrib = {'id':modelreactiondict['rxid']}) tree = ET.ElementTree(root) #tree.write(str(filename)) tree.write(filename) return
def merge_results(xml_files): failures = 0 tests = 0 errors = 0 time = 0.0 cases = [] for file_name in xml_files: tree = ET.parse(file_name) test_suite = tree.getroot() failures += int(test_suite.attrib['failures']) tests += int(test_suite.attrib['tests']) errors += int(test_suite.attrib['errors']) time += float(test_suite.attrib['time']) cases.append(test_suite.getchildren()) new_root = ET.Element('testsuite') new_root.attrib['failures'] = '%s' % failures new_root.attrib['tests'] = '%s' % tests new_root.attrib['errors'] = '%s' % errors new_root.attrib['time'] = '%s' % time for case in cases: new_root.extend(case) new_tree = ET.ElementTree(new_root) ET.dump(new_tree)
def addFavorite(nme,urls,iconimage,fan,md,playlist=None,regexs=None): if not os.path.isfile(os.path.join(favorites, 'fav.xml')): tmp = open(os.path.join(favorites, 'fav.xml'), 'w') tmp.close addon_log('Adding Favorites list') try: tree = ET.parse(os.path.join(favorites, 'fav.xml')) root = tree.getroot() if not root.tag == "favorites": favs = ET.Element('favorates') fav = ET.SubElement(favs, 'favorite') name = ET.SubElement(fav, 'name') name.text = nme url = ET.SubElement(fav, 'url') url.text = urls thumbnail = ET.SubElement(fav,'thumbnail') thumbnail.text = iconimage fanart = ET.SubElement(fav,'fanart') fanart.text = fan mode = ET.SubElement(fav,'mode') mode.text = md else: fav = ET.Element('favorite') name = ET.SubElement(fav, nme) url = ET.SubElement(fav, urls) thumbnail = ET.SubElement(fav, iconimage) fanart = ET.SubElement(fav, fan) mode = ET.SubElement(fav, md) ET.dump(fav) except: pass
def result_to_xml(result=''): now = datetime.datetime.now() min = now.minute sec = now.second filename = "result.xml" root = xml.Element("Train") root.set("name", "Ideenzug") kiwa = xml.SubElement(root, "MultifunctionArea") num_element = xml.Element("Number") num_element.text = "1" kiwa.append(num_element) OccupationState = xml.Element("OccupationState") print('sec:', sec) OccupationState.text = result OccupationType = xml.Element("OccupationType") OccupationType.text = "KINDERWAGEN" kiwa.append(OccupationState) kiwa.append(OccupationType) xml.dump(root) tree = xml.ElementTree(root) with open(filename, "w") as fh: tree.write(fh)
def result_to_xml_demo(result=''): now = datetime.datetime.now() min = now.minute sec = now.second filename = "result.xml" root = xml.Element("Train") root.set("name", "Ideenzug") kiwa = xml.SubElement(root, "MultifunctionArea") num_element = xml.Element("Number") num_element.text = "1" kiwa.append(num_element) OccupationState = xml.Element("OccupationState") print('sec:', sec) if (sec > 11 and sec < 20) or (sec > 41 and sec < 50): OccupationState.text = "FREE" OccupationType = xml.Element("OccupationType") OccupationType.text = "KINDERWAGEN" kiwa.append(OccupationState) kiwa.append(OccupationType) else: OccupationState.text = "OCCUPIED" OccupationType = xml.Element("OccupationType") OccupationType.text = "Kinderwagen" kiwa.append(OccupationState) kiwa.append(OccupationType) xml.dump(root) tree = xml.ElementTree(root) with open(filename, "w") as fh: tree.write(fh)
def test_dont_modify_trees(): t = kid.Template(source="<a>$xml</a>") t.xml = ElementTree.fromstring("<b>some<c>nested</c>elements</b>") expected = "<a><b>some<c>nested</c>elements</b></a>" assert t.serialize(fragment=True) == expected print ElementTree.dump(t.xml) assert t.serialize(fragment=True) == expected
def to_xml(docid): #et = etree.ElementTree() mf = open('%s.tab' % docid) gf = open('%s.groups' % docid) pf = open('%s.pairs' % docid) root = etree.Element('documents') d = etree.SubElement(root, 'document', {'id': docid}) groups = parse_groups(gf) pairs = parse_pairs(pf) with open(docid, 'r') as f: docid = 'OFC/2.txt' #os.path.basename(path) text, tok_ids, tokens = text_tokenized(docid.split('.')[0], docid) for antc, anph in pairs.iteritems(): chain = etree.SubElement(d, 'chain') i = tok_ids.index( group_id('2', int(groups[antc][0].split(',')[0]))) ii = len(' '.join([tokens[group_id(docid, int(x))][0] for x in groups[antc][0].split(',')])) j = tok_ids.index( group_id('2', int(groups[anph][0].split(',')[0]))) jj = len(' '.join([tokens[group_id(docid, int(x))][0] for x in groups[anph][0].split(',')])) ac = etree.SubElement(chain, 'item', {'sh': str(i), 'len': str(ii)}) c1 = etree.SubElement(ac, 'cont', {}) an = etree.SubElement(chain, 'item', {'sh': str(j), 'len': str(jj)}) c2 = etree.SubElement(an, 'cont', {}) print etree.dump(root)
def initMulticopy(): print "\nPlease select folder locations to copy to." print "\nThese folder locations will be saved/cached, which you can\n" \ + "update later." print "\nWhen you are done loading in locations, simply\n" \ + "press the cancel button in the file explorer.\n" try: tree = ET.parse('filecopylocations.xml') xroot = tree.getroot() for locs in xroot.findall('Location'): xroot.remove(locs) except: froot = ET.Element('Directories') tree = ET.ElementTree(froot) tree.write('filecopylocations.xml') tree = ET.parse('filecopylocations.xml') xroot = tree.getroot() locnum = 1 floc = getFolderLocation() while(floc != ''): try: loc = ET.SubElement(xroot, 'Location'.format(locnum)) loc.set('index', '{0}'.format(locnum)) locnum = locnum + 1 loc.text = floc floc = getFolderLocation() except: floc = '' tree.write('filecopylocations.xml') ET.dump(xroot)
def callback(results): reactor.stop() for success, result in results: if success: print ElementTree.dump(result) else: print result.printTraceback()
def printXML(line, cookies, info): allxml = ET.Element('url', {'site': line.strip()}) for cookie in cookies: child = ET.SubElement(allxml, 'cookie') secure = cookie.secure httponly = cookie.has_nonstandard_attr("HttpOnly") if not httponly: httponlyResult = "NO" else: httponlyResult = "YES" if not secure: secureResult = "NO" else: secureResult = "YES" ET.SubElement(child, 'name').text = cookie.name ET.SubElement(child, 'secure').text = secureResult ET.SubElement(child, 'httponly').text = httponlyResult if info: if cookie.expires is not None: expires = datetime.datetime.fromtimestamp(cookie.expires).strftime('%Y-%m-%d %H:%M:%S') else: expires = "Never" ET.SubElement(child, 'value').text = cookie.value ET.SubElement(child, 'path').text = cookie.path ET.SubElement(child, 'expires').text = expires indent(allxml) ET.dump(allxml)
def main(): # PARSE BOOKMARKS bookmarks_json = parse_bookmarks() # OUTPUT XMIND # - CREATE BASE XML TREE # xmap content # sheet # title # children # topics xmap_content_attrs = { "xmlns" : "urn:xmind:xmap:xmlns:content:2.0", "xmlns:fo" : "http://www.w3.org/1999/XSL/Format", "xmlns:svg" : "http://www.w3.org/2000/svg", "xmlns:xhtml" : "http://www.w3.org/1999/xhtml", "xmlns:xlink" : "http://www.w3.org/1999/xlink", "version" : "2.0", "timestamp" : current_time() } xmap_content = ET.Element('xmap-content', xmap_content_attrs) sheet_attrs = {"id":create_id(), "timestamp":current_time()} sheet = ET.SubElement(xmap_content, 'sheet', sheet_attrs) sheet_title = ET.SubElement(sheet, 'title') sheet_title.text = "Chrome Bookmarks" root_topic_attrs = {"id":create_id(), "timestamp":current_time()} root_topic = ET.SubElement(sheet, 'topic', root_topic_attrs) root_topic_title = ET.SubElement(root_topic, 'title') root_topic_title.text = "Chrome Bookmarks" tree = ET.ElementTree(xmap_content) # - WALK JSON AND CONVERT TO XML walk_bookmarks(bookmarks_json["roots"]["bookmark_bar"], root_topic) ET.dump(tree)
def intiMulticopy(self): fio = fIO() fio.filePrompt("folder", "Please select folder locations to copy to.\n" + "These folder locations will be saved.\n" + "When you are done loading in locations, simply\n" + "press the cancel button in the file explorer.\n") try: tree = ET.parse('filecopylocations.xml') xroot = tree.getroot() for locs in xroot.findall('Location'): xroot.remove(locs) except: froot = ET.Element('Directories') tree = ET.ElementTree(froot) tree.write('filecopylocations.xml') tree = ET.parse('filecopylocations.xml') xroot = tree.getroot() locnum = 1 fio.folderLocation() floc = fio.getFolderLocation() while(floc != ''): try: loc = ET.SubElement(xroot, 'Location'.format(locnum)) loc.set('index', '{0}'.format(locnum)) locnum = locnum + 1 loc.text = floc floc = fio.getFolderLocation() except: floc = '' tree.write('filecopylocations.xml') ET.dump(xroot)
def create_xml_version(self): location = ET.Element("location") elements_dict = { 'name': 'str', 'slug': 'str', 'is_phone': 'bool', 'is_street_address': 'bool', 'date_added': 'date', 'date_modified': 'date'} for elementName, elementType in elements_dict.iteritems(): newElement = ET.SubElement(location, elementName) if elementType == 'str': newElement.text = getattr(self, elementName) elif elementType == 'bool': bool_var = getattr(self, elementName) newElement.text = str(bool_var) elif elementType == 'date': # do something else date = getattr(self, elementName) date_as_string = date.strftime('%Y-%m-%d') newElement.text = date_as_string else: print "Don't know what to do here." print "unknown element type." print 5/0 ET.dump(location) return(ET)
def main(): if len(sys.argv) <= 1: print ("usage: query.py <zipcode,zipcode,...> <filter>\n example: query.py M40,M50,1090 Pizza") return zipcodes = sys.argv[1].split(",") food_type = "" if len(sys.argv) >= 3: food_type = sys.argv[2] xmls = [] for zipcode in zipcodes: url = DAPPER_URL.replace("ZIPCODE", zipcode) url = url.replace("FILTER", food_type) req = urllib.urlopen(url) xmls.append(ET.fromstring(req.read())) count = 0 out = ET.Element("restaurants") for et in xmls: for r in et.findall("./restaurant"): count += 1 restaurant = ET.SubElement(out, "restaurant") for name in r.iter("name"): name = ET.SubElement(restaurant, "name") name.text = r.find("name").text print ET.dump(out) print ("found %d restaurants" % count)
def multicopy(): try: tree = ET.parse('filecopylocations.xml') xroot = tree.getroot() print "\nWould you like to edit the following copy desitinations?\n" ET.dump(xroot) edit = raw_input("\ny=yes : n=no\n") if edit == 'y': initMulticopy() else: pass except: initMulticopy() tree = ET.parse('filecopylocations.xml') xroot = tree.getroot() print "\nPlease select the file you wish to have copied." try: fcpyfrom = getFileLocation() fcpyname = getFileNameFromFilePath(fcpyfrom) fcpyfrom = open(fcpyfrom, 'r').read() for loc in xroot.findall('Location'): f = open(loc.text + '/' + fcpyname, 'w') f.write(fcpyfrom) f.close() print "\nFile was successfully copied!" except: print "\nCould not copy file!" pass
def createWorkflow( self, experimentID,projectID, pipeline,status): """Create a Workflow Entry and return the primary key of the inserted workflow""" WorkflowStrXML = '<wrk:Workflow data_type="xnat:mrSessionData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wrk="http://nrg.wustl.edu/workflow" />' WorkflowDataElement = ET.fromstring(WorkflowStrXML) ET.register_namespace('wrk', 'http://nrg.wustl.edu/workflow') WorkflowDataElement.set('ID',experimentID) WorkflowDataElement.set('ExternalID',projectID) WorkflowDataElement.set('status',status) WorkflowDataElement.set('pipeline_name',pipeline) timeNow=time.localtime() xmlTime=time.strftime('%Y-%m-%dT%H:%M:%S', timeNow) prettyTimeNow=time.strftime('%Y-%m-%dT%H-%M-%S', timeNow) WorkflowDataElement.set('launch_time',xmlTime) WorkflowDataStr = ET.tostring(WorkflowDataElement) if sys.platform != 'win32': WorkflowWriteStr = '/tmp/Workflow_%s_%s.xml' % (experimentID,prettyTimeNow) with open(WorkflowWriteStr, 'wb') as outputFileObj: outputFileObj.write(WorkflowDataStr) #WorkflowSubmitStr = 'source $SCRIPTS_HOME/xnat-tools_setup.sh; $NRG_PACKAGES/tools/xnat-tools/StoreXML -u %s -p %s -host %s -location %s -allowDataDeletion true' % (self.User, self.Password, self.Server, WorkflowWriteStr) WorkflowSubmitStr = '$PIPELINE_HOME/xnat-tools/XNATRestClient -m PUT -user_session %s -host %s -remote "REST/workflows?req_format=xml" -local %s' % (self.JSESSION, self.Server, WorkflowWriteStr) subprocess.call(WorkflowSubmitStr, shell=True, stdout = open("/dev/null", "w")) workflowID = self.getQueuedWorkflowIdAsParameter(pipeline,experimentID) return workflowID else: ET.dump(WorkflowDataElement) return -1
def read_page(host,port,url,user,password): url_tomcat = "http://"+host+":"+port+url if args.verbosity: print "connection url: %s\n"%(url_tomcat) password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None,url_tomcat,user,password) handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener=urllib2.build_opener(handler) urllib2.install_opener(opener) req = urllib2.Request(url_tomcat) handle = urllib2.urlopen(req,None,5) # Store all page in a variable page = handle.read() # End of Open manager status if args.verbosity>2: print "page "+url_tomcat+" content:" print page # Read xml string root = ET.fromstring(page) if args.verbosity>1: print ET.dump(root) return root
def from_smdx(self, element): """ Sets the block type attributes based on an element tree block type element contained in an SMDX model definition. Parameters: element : Element Tree block type element. """ btype = element.attrib.get(smdx.SMDX_ATTR_TYPE, smdx.SMDX_ATTR_TYPE_FIXED) if btype != smdx.SMDX_ATTR_TYPE_FIXED and btype != smdx.SMDX_ATTR_TYPE_REPEATING: raise SunSpecError('Invalid block type') self.type = smdx.smdx_block_types.get(btype) self.len = element.attrib.get(smdx.SMDX_ATTR_LEN) if self.len is None: raise SunSpecError('Block len error') self.name = element.attrib.get(smdx.SMDX_ATTR_NAME) if self.name is None: self.name = self.type # process points for e in element.findall(smdx.SMDX_POINT): pt = PointType(block_type=self) pt.from_smdx(e) if self.points.get(pt.id) is not None: ET.dump(e) raise SunSpecError('Duplicate point definition: %s' % (pt.id)) self.points_list.append(pt) self.points[pt.id] = pt
def add_cmd(cmdlist): print("add") if "rec" == cmdlist[1]: #add rec date type desc banlance,num .. if dictTypeList.get(cmdlist[3]) is None: print("typeerr:"+cmdlist[3]) return rec = ET.Element('rec') rec.set("date",cmdlist[2]) rec.set("type",cmdlist[3]) rec.set("desc",cmdlist[4]) for i in range(5,len(cmdlist)): subban =cmdlist[i].split(",") item = ET.SubElement(rec, 'item') item.set("banlance",subban[0]) item.set("num",subban[1]) else: print("endfor") reclist_et = xmlfile.find("recordlist") reclist_et.append(rec) print(ET.dump(xmlfile)) #reclist_et.append(rec) #print(ET.tostring(xmlfile)) elif "banlance" == cmdlist[1]: banitem = ET.Element("item") banitem.set("name",cmdlist[2]) banitem.set("id",cmdlist[3]) banitem.set("desc",cmdlist[4]) banitem.set("date",cmdlist[5]) banitem.set("init",cmdlist[6]) banlist_et = xmlfile.find("banlancelist") banlist_et.append(banitem) print(ET.dump(xmlfile)) print("addend")
def result_set(obj): items = ET.Element('items') for task_set in obj.task_sets: Alfred.task_set(items, task_set) for task in obj.tasks: Alfred.task(items, task) ET.dump(items)
def dump_etree(self): """ Dump etree to console for debugging Returns: """ self.logger.info('Dumping XML etree to console') Et.dump(self.etree)
def dump_content(): d_data = init_gpg() if d_data is False: error_print("File doesn't exist!") else: tree = ET.ElementTree(ET.fromstring(d_data.data)) ET.dump(tree.getroot())
def parse(self, filename): retDict = {} tree = ET.parse(fu.normalizeName(filename)) root = tree.getroot() if 'configuration' != root.tag: raise ValueError('invalid root tag: ' + root.tag) for prop in root: if 'configuration' == prop.tag: retDict.update(self.parse(prop.text)) continue if 'property' != prop.tag: raise ValueError('invalid property tag: ' + prop.tag) key = None val = None for field in prop: if 'name' == field.tag: #name should not have child if len(list(field)) != 0: raise SyntaxError('name should not have child:' '%s' %ET.dump(field)) key = field.text if 'value' == field.tag: #value should not have child if len(list(field)) != 0: raise SyntaxError('value should not have child:' '%s' %ET.dump(field)) val = field.text if (key == None) or (val == None): raise SyntaxError('no key or value for prop:' '%s' %ET.dump(prop)) retDict[key] = val return retDict
def generate_default(self): root = ET.fromstring(JENKINS_XML.DEFAULT_XML) ET.dump(root)
# string.isspace() 判斷是否字符串爲space # 構建xml文檔 import xml.etree.ElementTree as ET data = ET.Element('Data') book = ET.Element('Book') author = ET.Element('Author') # 設置屬性 book.set('x', 'abc') # 設置文本內容 author.text = 'Desmond' data.append(book) book.append(author) # 查看xml形式 ET.dump(data) # 也可以通過SubElement直接加子節點 data = ET.Element('Data') book = ET.SubElement(data, 'Book') book.set('x', 'abc') # 創建ElementTree對象並寫入文件 et = ET.ElementTree(data) et.write('test.xml', encoding='utf8') # 讀寫excel import xlrd book = xlrd.open_workbook('demo.xlsx') # 返回所有的sheet,一個excel中可以開多個sheet
# if int(year.text) > 2000: # year2=ET.Element('year2') # year2.text='111' # year2.attrib={'a':'111'} # country.append(year2) # tree.write('bbb.xml',encoding="utf-8",xml_declaration=True) # tree.write('bbb.xml') # # new_xml = ET.Element('namelist') # 初始化一个namelist节点,获取一个对象new_xml # name = ET.SubElement(new_xml, "name_s", attrib={"enrolled": "yes"}) # 初始化一个子节点 import xml.etree.ElementTree as ET new_xml = ET.Element("namelist") # 生成名叫namelist的子节点 name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"}) # 在namelist下生成名叫name的子节点 age = ET.SubElement(name, "age", attrib={"checked": "no"}) sex = ET.SubElement(name, "sex") sex.text = '33' name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"}) age = ET.SubElement(name2, "age") age.text = '19' et = ET.ElementTree(new_xml) # 生成文档对象 et.write("test.xml", encoding="utf-8", xml_declaration=True) # 写到文件去,最后声明是xml格式 ET.dump(new_xml) # 打印生成的
SPREADSHEET_NAMESPACE = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}' CELL = SPREADSHEET_NAMESPACE + 'c' VALUE = SPREADSHEET_NAMESPACE + 'v' FORMULA = SPREADSHEET_NAMESPACE + "f" xml = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"><dimension ref="A1:C5" /><sheetViews><sheetView tabSelected="1" showRuler="0" zoomScale="85" workbookViewId="0"><selection activeCell="A5" sqref="A5:C5" /></sheetView></sheetViews><sheetFormatPr baseColWidth="10" defaultRowHeight="16" x14ac:dyDescent="0.2" /><sheetData><row r="1" spans="1:3" x14ac:dyDescent="0.2"><c r="A1" t="s"><v>0</v></c><c r="B1" t="s"><v>1</v></c><c r="C1" t="s"><v>2</v></c></row></sheetData><pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3" /></worksheet>""" import xml.etree.ElementTree as ET root = ET.fromstring(xml) print(ET.dump(root))
displayname = ET.SubElement(channel, 'display-name') displayname.attrib = {'lang': 'cs'} displayname.text = channeltext for channel in epgdata['channels']: for event in epgdata['channels'][channel]: programme = ET.SubElement(tv, 'programme') l_start = datetime.datetime.strptime(event['startTime'], "%Y-%m-%d %H:%M") l_stop = datetime.datetime.strptime(event['endTime'], "%Y-%m-%d %H:%M") programme.attrib = { 'start': l_start.strftime("%Y%m%d%H%M%S ") + local, 'stop': l_stop.strftime("%Y%m%d%H%M%S ") + local, 'channel': channel } title = ET.SubElement(programme, 'title') title.text = event['title'] title.attrib = {'lang': 'cs'} desc = ET.SubElement(programme, 'desc') desc.text = event['description'] desc.attrib = {'lang': 'cs'} date = ET.SubElement(programme, 'date') date.text = l_start.strftime("%Y%m%d") ET.dump(tv)
def dump_ticket(dump_format, xml): """ Prints xml ticket into pretty format for user: dump_format: last, brief, detail, xml, full """ def totext(arg): """ Gets text from XML object """ if arg is None or arg.text is None: return "None" else: return arg.text def dump_title(): """ Prints brief title for ticket """ print( "{0: <10} {1: >15} {2: >10}/{3: <10} {4: >20} {5: >20} {6: <100}".format( id, status, group, user, host, vticket, desc, )) def dump_comment(lastonly): print(" Description:") for line in xml.find("DESCRIPTION").text.split("\n"): print("\t{}".format(line)) parse_comment(xml.find("COMMENTS").text, "Resolver Comment") parse_comment(xml.find("HELP_CUSTOMER_COMMENTS").text, "User Comment") mkeys = list(msgs.keys()) mkeys.sort() for dt in mkeys: for ctype, cmsgs in msgs[dt].items(): for cmsg in cmsgs: print(" %s %s: %s" % (dt, ctype, cmsg['user'])) for line in cmsg['text'].split("\n"): print("\t{}".format(line)) if lastonly: return def parse_comment(cmt, ctype): txt = [] dt = None user = None for line in cmt.split("\n"): match = re.search('^(?P<date>[A-Z][a-z][a-z]\s+\d+,\s+\d{4}\s+\d+:\d+:\d+\s+(?:AM|PM))\s+(?P<user>\w+)$', line) if match: if dt: #push new message on stack msgs[dt][ctype].append({ 'user': user, 'text': "\n".join(txt) }) txt = [] user = None dt = None #Aug 30, 2013 4:10:58 PM jirina user = match.group('user') dt = datetime.strptime(match.group('date'), '%b %d, %Y %I:%M:%S %p') if not dt in msgs: msgs[dt] = {} if not ctype in msgs[dt]: msgs[dt][ctype] = [] else: txt.append(line) if dt: #push last message on stack msgs[dt][ctype].append({ 'user': user, 'text': "\n".join(txt) }) id = totext(xml.find('ID')) status = totext(xml.find('STATUS')) group = totext(xml.find('HELP_ASSIGN_GROUP')) user = totext(xml.find('ASSIGNED_TO')) host = totext(xml.find('HELP_HOSTNAME_OTHER')) vticket = totext(xml.find('HELP_VENDOR_TICKET')) desc = totext(xml.find('SHORT_DESCR')) msgs = {} #messages by time if host is None: host = "-" if vticket is None: vticket = "-" if dump_format == "xml": ElementTree.dump(xml) elif dump_format == "brief": dump_title() elif dump_format == "full": dump_title() dump_comment(False) elif dump_format == "last": dump_title() dump_comment(True) elif dump_format == "detail": for child in xml: if child.text: for line in child.text.split("\n"): print("%s: %s" % (child.tag, line))
def search(): """ Search Extraview Tickets Usage: ev_search [-b | --brief | -l | --last | -d | --detail | -x | --xml | -f | --full] GROUP [USER] [KEYWORD] [STATUS] ev_search (-b | --brief | -l | --last | -d | --detail | -x | --xml | -f | --full) [-g GROUP | --group GROUP] [-u USER | --user USER] [-k KEYWORD | --keyword KEYWORD] [-s STATUS | --status STATUS] [-m MAX | --max MAX] [--days DAYS] ev_search (-h | --help) Arguments: GROUP Search for tickets assigned to this group USER Search for tickets assigned to this user KEYWORD Search for any ticket with this keyword STATUS Search for any ticket with this status. Can be Assigned, Transferred, Stalled, Closed, or All. Options: -h, --help -g, --group Search for tickets assigned to this group -u, --user Search for tickets assigned to this user -k, --keyword Search for any ticket with this keyword. -s, --status Search for any ticket with this status. -m, --max Maxium number of tickets to search against (Default: 200) --days Maxium number of days to search against ticket open date (Default: 365 days) -f, --full Print generally most useful information in ticket -d, --detail Print all known content of Extraivew ticket -b, --brief Print very brief description of ticket -l, --last Print last update to ticket -x, --xml Print xml content of ticket """ args = docopt.docopt(search.__doc__) ret = 0 found = 0 EV = connect() max_tickets = 200 max_days = 365 fields = { } if args['MAX']: max_tickets= int(args['MAX']) if args['DAYS']: max_days = int(args['DAYS']) if args['GROUP']: fields['*HELP_ASSIGN_GROUP'] = args['GROUP'] if args['USER']: fields['*ASSIGNED_TO'] = args['USER'] if args['KEYWORD']: fields['keyword'] = args['KEYWORD'] if args['STATUS']: fields['*STATUS'] = args['STATUS'] if args['STATUS'] is None: fields['STATUS'] = "STALLED;TRANSFERRED;ASSIGNED" fields['date'] = '-%s' % (datetime.isoformat( datetime.today() - timedelta(days=1) )) result = EV.search(fields, max_tickets) for ticket in result.iterfind('PROBLEM_RECORD'): found += 1 if args['--xml']: dump_ticket('xml', ticket) elif args['--brief']: dump_ticket('brief', ticket) elif args['--detail']: dump_ticket('detail', ticket) elif args['--full']: dump_ticket('full', ticket) elif args['--last']: dump_ticket('last', ticket) else: dump_ticket('brief', ticket) if not found: ElementTree.dump(result) vlog(1, 'Nothing found.') ret += 1 sys.exit(ret)
from flickrapi import FlickrAPI class keys: apikey = u'a233c66549c9fb5e40a68c1ae156b370' apisecret = u'03fbb3ea705fe096' print('Creating FlickrAPI object') flickr = FlickrAPI(keys.apikey, keys.apisecret) # ------------------------------------------------------------------------------ print('Step 1: authenticate') flickr.authenticate_via_browser(perms='delete') # ------------------------------------------------------------------------------ print('Step 2: Upload photo') resp = flickr.upload('tests/photo.jpg', is_public=0, is_friend=0, is_family=0) from xml.etree import ElementTree as ET ET.dump(resp) photo_id = resp.findtext('photoid') # ------------------------------------------------------------------------------ print('Step 3: Replace photo') flickr.replace('jaguar.jpg', photo_id=photo_id) # ------------------------------------------------------------------------------ print('Step 4: Delete photo') flickr.photos.delete(photo_id=photo_id)
<gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> </data> """ import xml.etree.ElementTree as ET root = ET.fromstring(country_data_as_string) for child in root: print(child.tag, child.attrib) for neighbor in root.iter('neighbor'): print(neighbor.attrib) for country in root.findall('country'): rank = country.find('rank').text name = country.get('name') print(name, rank) for rank in root.iter('rank'): new_rank = int(rank.text) + 1 rank.text = str(new_rank) rank.set('updated', 'yes') tree.write('output.xml') print([ET.dump(element) for element in root])
def __str__(self): return ET.dump(self.xml)
def build_country(): a = ET.Element('data') b = ET.SubElement(a, 'country') c = ET.SubElement(b, 'year') d = ET.SubElement(a, 'country') ET.dump(a)
#!/usr/bin/env python # -*-coding:utf-8-*- # 自己创建xml文档 import xml.etree.ElementTree as ET new_xml = ET.Element("namelist") name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"}) age = ET.SubElement(name, "age", attrib={"checked": "no"}) sex = ET.SubElement(name, "sex") sex.text = '33' name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"}) age = ET.SubElement(name2, "age") age.text = '19' et = ET.ElementTree(new_xml) # 生成文档对象 et.write("test.xml", encoding="utf-8", xml_declaration=True) ET.dump(new_xml) # 打印生成的格式
# print(lats_lons_csv) # adicionando os atributos no elemento wpt ET.register_namespace('', 'http://www.topografix.com/GPX/1/1') ET.register_namespace("xsi", 'http://www.w3.org/2001/XMLSchema-instance') tree = ET.parse('input_model.xml') #importa o xml e atribiu na árvore root = tree.getroot() # wpt_atributos={} # wpt=ET.Element('wpt') # name=ET.SubElement(wpt, 'name') # category=ET.SubElement(wpt, 'category') # wpt.attrib={'lat':'-fdfdf','lon':'fodkofdk'} <== exemplo para atributos lat lon # name.text='nome' <== exemplo para texto # category.text='categoria'<== exemplo para texto # root.append(wpt) <== adiciona o elemento wpt para árvore # print(lats_lons_csv[5]) i = 0 name = [''] for rows in lats_lons_csv: wpt = ET.Element('wpt', lats_lons_csv[i]) name = ET.SubElement(wpt, 'name') name.text = names_csv[i] category = ET.SubElement(wpt, 'category') category.text = categorys_csv[i] root.append(wpt) i = i + 1 ET.dump(tree) print(os.name) #print(len(i1.head[0])) tree.write(path_output, encoding='UTF-8')
... } """ refentry = tree.fromstring(TEMPLATE) for name, directives in directive_groups.items(): _make_section(refentry, name, directives) return refentry def make_page(xml_files): "Extract directives from xml_files and return XML index tree." directive_groups = { name: collections.defaultdict(list) for name in [ 'unit-directives', 'udev-directives', 'systemd-directives', 'journal-directives', ] } for page in xml_files: _extract_directives(directive_groups, page) return _make_page(directive_groups) if __name__ == '__main__': tree.dump(make_page(sys.argv[1:]))
# for i in tree.iter('ip'): # print(i.attrib, i.text) # for i in root: # print(i.attrib) # for a in i.attrib: # print(a) # if i.attrib == "FUT-BOOK-1": # print(123) # print(i) # for i in root.findall('MarketDataGroup'): # for j in i.findall('connections'): # for x in j.findall('connection'): # print(x.find('ip').text, x.find('port').text) # # for y in x.findall('ip'): # # print(y.text) # # print(root[1][0][0][3].text) # for i in tree.iter('port'): # tree.remove(i) connections = ElementTree.Element('new_cont') type = ElementTree.SubElement(connections, 'new_c').set('bb', 'aa') ElementTree.dump(connections) tree.write('C:\share\TestFAST\ptest_internet\configuration_1.xml') file1.close()
'''for i in range(0,100): print(timeit("'Hello, world!'.replace('Hello', 'Goodbye')"))''' # Start counting. start_time = time() # Take the original function's return value. # Calculate the elapsed time. bd = ET.Element("base") ventana = ET.SubElement(bd, "ventana", name="ventana-consultas") ventana_hide = ET.SubElement( ventana, "ventana-hide", ) ventana_hide.set("option-hide", "false") ET.dump(bd) tree = ET.ElementTree(bd) tree.write("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") estructura_xml = ET.parse("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") # Obtiene el elemento raíz: raiz = estructura_xml.getroot() '''for ventana in raiz.findall('ventana'): print(ventana) print("espacio1") print(ventana.get("option-hide")) print("nada") ''' for ventana in raiz.iter('ventana'): print("get: " + str(ventana.get("option-hide")))
def dump(self): ET.dump(self._tree)
# age.text = "22" # 设置属性值 # sex = ET.SubElement(name_1, "sex") # sex.text = "Man" # 第二个node ,重复上面操作 name_2 = ET.SubElement(new_xml, "name", attrib={"id": "10002"}) # age = ET.SubElement(name_2, "age") # 通过指定上级目录名称,确认层级关系 # age.text = "33" # 设置属性值 # sex = ET.SubElement(name_2, "sex") # sex.text = "Man" et = ET.ElementTree(new_xml) # 生成一个文档对象 et.write("create_xml.xml", encoding="utf-8", xml_declaration=True) # xml_declaration=True 声明xml格式 ET.dump(new_xml) # new_xml = ET.Element("namelist") # # name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"}) # age = ET.SubElement(name, "age", attrib={"checked": "no"}) # sex = ET.SubElement(name, "sex") # sex.text = '33' # # name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"}) # age = ET.SubElement(name2, "age") # age.text = '19' # # et = ET.ElementTree(new_xml) # 生成文档对象 # et.write("test.xml", encoding="utf-8", xml_declaration=True) #
def loadnetconfqbv(configdata): print(configdata); print(type(configdata)); interfaces = ET.Element('interfaces'); interfaces.set('xmlns', 'urn:ietf:params:xml:ns:yang:ietf-interfaces'); interfaces.set('xmlns:sched', 'urn:ieee:std:802.1Q:yang:ieee802-dot1q-sched'); interfaces.set('xmlns:preempt', 'urn:ieee:std:802.1Q:yang:ieee802-dot1q-preemption'); interfaces.set('xmlns:ianaift', 'urn:ietf:params:xml:ns:yang:iana-if-type'); port = ET.SubElement(interfaces, 'interface'); iname = ET.SubElement(port, 'name'); iname.text = configdata['port']; enable = ET.SubElement(port, 'enabled'); enable.text = 'true'; itype = ET.SubElement(port, 'type'); itype.text = 'ianaift:ethernetCsmacd'; admin = ET.SubElement(port, 'sched:gate-parameters'); gate_enable = ET.SubElement(admin, 'sched:gate-enabled'); gate_enable.text = configdata['enable']; configchange = ET.SubElement(admin, 'sched:config-change'); configchange.text = 'true'; #admin = ET.SubElement(port, 'admin'); print(configdata['enable']); if (configdata['enable'] == 'false'): prettyXml(interfaces); ET.dump(interfaces); qbvxmlb = ET.tostring(interfaces, encoding='utf8', method='xml'); qbvxmlstr = str(qbvxmlb, encoding='utf-8'); return loadNetconf(qbvxmlstr, configdata['device']); listlen = ET.SubElement(admin, 'sched:admin-control-list-length'); listlen.text = str(len(configdata['entry'])); for i in range(len(configdata['entry'])): gatelist = ET.SubElement(admin,'sched:admin-control-list'); gindex = ET.SubElement(gatelist, 'sched:index'); gindex.text = str(i); #gce = ET.SubElement(gatelist, 'gate-control-entry'); oname = ET.SubElement(gatelist, 'sched:operation-name'); oname.text = 'sched:set-gate-states'; gentry = ET.SubElement(gatelist, 'sched:sgs-params'); gatestate = ET.SubElement(gentry, 'sched:gate-states-value'); gatestate.text = str(configdata['entry'][i]['gate']); ti = ET.SubElement(gentry, 'sched:time-interval-value'); ti.text = str(configdata['entry'][i]['period']); #cycletime = ET.SubElement(admin, 'admin-cycle-time'); #cycletime.text = '200000'; if configdata.__contains__('basetime'): xs,zs=math.modf(float(configdata['basetime'])); xsstr = str(xs).split('.'); if (len(xsstr[1]) > 8): xshu = xsstr[1][0:9]; else: xshu = xsstr[1].ljust(9, '0'); basetime = ET.SubElement(admin, 'sched:admin-base-time'); seconds = ET.SubElement(basetime, 'sched:seconds'); seconds.text = str(int(zs)); fragseconds = ET.SubElement(basetime, 'sched:fractional-seconds'); fragseconds.text = xshu; prettyXml(interfaces); #ET.dump(tsn); qbvxmlb = ET.tostring(interfaces, encoding='utf8', method='xml'); qbvxmlstr = str(qbvxmlb, encoding='utf-8'); return loadNetconf(qbvxmlstr, configdata['device']);
upWeibullElement.append(createElement("k", text="1.5")) upWeibullElement.append(createElement("lambda", text="1.0")) upWeibullElement.append(createElement("upperBound",text="10.0")) upWeibull = getDistribution(upWeibullElement) #Testing N-Dimensional Distributions #InverseWeight ndInverseWeightElement = ET.Element("NDInverseWeight",{"name":"test"}) ndInverseWeightElement.append(createElement("workingDir", text="ND_test_Grid_cdf/")) ndInverseWeightElement.append(createElement("p", text="0.5")) filenode = createElement("dataFilename", text="2DgaussianScatteredPDF.txt") filenode.set("type","PDF") ndInverseWeightElement.append(filenode) ET.dump(ndInverseWeightElement) ndInverseWeight_test = getDistribution(ndInverseWeightElement) ## Should these be checked? initParams = ndInverseWeight_test.getInitParams() checkCrowDist("NDInverseWeight",ndInverseWeight_test,{'type': 'NDInverseWeightDistribution'}) #Cartesian Spline ndCartesianSplineElement = ET.Element("NDCartesianSpline",{"name":"test"}) filenode = createElement("dataFilename", text="2DgaussianCartesianPDF.txt") filenode.set("type","PDF") ndCartesianSplineElement.append(filenode) ndCartesianSplineElement.append(createElement("workingDir", text="ND_test_Grid_cdf/"))
""" root2 = ET.fromstring(xml) # 读取字符串 print(root2.findall(".")) # 找到根元素 print(root2.findall("./country/neighbor")) # 找到根元素下指定的元素 print(root2.findall(".//neighbor[2]")) # 第二个子元素下的所有neighbor元素 print(root2.findall(".//year/..[@name='Singapore']")) # 找到名为Singapore的元素,并且包含一个year子元素 print(root2.findall(".//*[@name='Singapore']/year")) # 找到Singapore元素下的year元素 print(root2.findall(".//*[@name='Singapore']/year")[0].text) # 访问Singapore元素下的year元素的文本内容 # 生成XML内容 r = ET.Element("root") # 创建根元素 a = ET.SubElement(r, 'sub1', attrib={'name': 'AAA', 'num': "111"}, con="test") # 创建子元素并添加属性 b = ET.SubElement(r, "sub2") # 创建子元素 b.attrib = {"name": "BBB"} # 添加属性 c = ET.SubElement(r, "sub3") # 创建子元素 c.text = "test3" # 添加文本 ET.dump(r) # 在标准输出显示元素的树结构(建议只用于调试) tree2 = ET.ElementTree(r) # 创建ElementTree对象 new_xml2 = 'Chapter13_StandradLibrary11_XML02-new2.xml' tree2.write(new_xml2) # 构建XML文档 os.remove(new_xml2) # ### xml package # - XML Processing Modules # - https://docs.python.org/3/library/xml.html # # ### 标准库xml.etree.ElementTree模块 # - The ElementTree XML API(实现用于解析和创建XML数据的简单有效的API) # - https://docs.python.org/3/library/xml.etree.elementtree.html
def transform(e): name = shorten(e.tag) assert e.tail is None if name == 't': assert len(e) == 0 return e.text elif name == 'instrText': assert len(e) == 0 if e.text.startswith(' SEQ ') or e.text.startswith(' REF '): return '{' + e.text + '}' return None elif name in { 'pPr', 'rPr', 'sectPr', 'tblPr', 'tblPrEx', 'trPr', 'tcPr', 'numPr' }: # Presentation data. return parse_pr(e) elif name == 'pPrChange': # A diff to a previous version of the document. return None elif name in { '{http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing}posOffset', '{http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing}pctWidth', '{http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing}pctHeight' }: # Layout data return None elif name == 'delText' or name == 'delInstrText': assert ALLOW_CHANGES return None else: assert e.text is None # Transform all children. css = {} c = [] def add(ht): if isinstance(ht, dict): css.update(ht) elif isinstance(ht, list): for item in ht: add(item) elif isinstance(ht, str) and c and isinstance(c[-1], str): # Merge adjacent strings. c[-1] += ht elif ht is not None: c.append(ht) for k in e: add(transform(k)) if not css: css = None if name == 'document': [body_e] = c return html(head(), body_e) elif name == 'body': return body(*c) elif name == 'r': if css is None: return c else: # No amount of style matters if there's no text here. if len(c) == 0: return None elif len(c) == 1 and isinstance(c[0], str) and c[0].strip() == '': return c[0] or None result = span(*c) result.style = css if css and '@cls' in css: result.attrs['class'] = css['@cls'] del css['@cls'] return result elif name == 'p': if len(c) == 0: return None result = p(*c) if css and '@cls' in css: result.attrs['class'] = css['@cls'] del css['@cls'] result.style = css return result elif name == 'pict': return div(*c, class_='w-pict') elif name == 'sym': assert not c attrs = {shorten(k): v for k, v in e.items()} if len(attrs ) == 2 and attrs['font'] == 'Symbol' and 'char' in attrs: _symbols = { 'F02D': '\u2212', # minus sign 'F070': '\u03C0', # greek small letter pi 'F0A3': '\u2264', # less-than or equal to 'F0A5': '\u221e', # infinity 'F0B3': '\u2265', # greater-than or equal to 'F0B4': '\u00d7', # multiplication sign 'F0B8': '\u00f7', # division sign 'F0B9': '\u2260', # not equal to 'F0CF': '\u2209', # not an element of 'F0D4': '\u2122', # trade mark sign 'F0E4': '\u2122' # trade mark sign (again) } ch = _symbols.get(attrs['char'], '\ufffd') # U+FFFD, replacement character if ch == '\ufffd': ch += ' (' + attrs['char'] + ')' ElementTree.dump(e) return ch ElementTree.dump(e) return None elif name == 'tab': assert not c assert not e.keys() return '\t' elif name == 'br': assert not c assert set(e.keys()) <= { '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}type' } br_type = e.get( '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}type' ) if br_type is None: return br() else: assert br_type == 'page' return hr() elif name == 'lastRenderedPageBreak': # This means "the last time we actually rendered this document to # pages, there was a page break here". Theoretically, this could be # used to show PDF page numbers in the HTML, but it's not worth it. # Everyone uses section numbers anyway. return None elif name == 'noBreakHyphen': # This appears 4 times in the document. The first 3 times it is a # mistake and U+2212 MINUS SIGN would be more appropriate. The last # time, a plain old hyphen would be better. return '\u2011' #non-breaking hyphen elif name in { 'bookmarkStart', 'bookmarkEnd', 'commentRangeStart', 'commentRangeEnd' }: return None elif name == 'tbl': assert not e.keys() tbl = table(*c, class_="real-table") if css: if '-ooxml-border-insideH' in css: # borders between rows row_border = css['-ooxml-border-insideH'] del css['-ooxml-border-insideH'] if '-ooxml-border-insideV' in css: # borders between columns col_border = css['-ooxml-border-insideV'] del css['-ooxml-border-insideV'] ##tbl.style = css return figure(tbl) elif name == 'tr': return tr(*c) elif name == 'tc': result = td(*c) result.style = css return result else: return c
import xml.etree.ElementTree as et stu = et.Element("Student1") name = et.SubElement(stu, 'Name') name.attrib = {'lang', 'en'} name.text = 'maozedong' age = et.SubElement(stu, 'Age') age.text = 18 et.dump(stu) # 这行什么问题
appsync = DellEMC_AppSync.DellEMC_AppSync(username=args.user, password=args.password, host=args.appsynchost, ssl=True, verify=False, verbose=args.verbose) response = appsync.get("/types/storageSystem/instances") if response.status_code != 200: print("Could not get storage arrays.") exit(1) else: array_dom = ET.ElementTree(ET.fromstring(response.text)) if args.verbose >= 3: ET.dump(array_dom) for array in array_dom.findall(".//storageSystem"): if args.verbose >= 1: print("Array:", array.find("displayName").text, "ID:", array.find("id").text) # Get devices from array array_dev_response = appsync.get("/instances/managedStorageSystem::" + array.find("id").text + "/relationships/PoolCopyDevices") # If we couldn't retreive devices for an array continue if array_dev_response.status_code != 200: continue
# -*-coding:utf-* import xml.etree.ElementTree as et stu = et.Element("Student") name = et.SubElement(stu, "Name") name.attrib = {"lang", "en"} name.text = "xiaoming" age = et.SubElement(stu, "Age") age.text = 18 et.dump(stu)
def print_tree(root, out_F): if out_F == sys.stdout: ET.dump(root) else: et = ET.ElementTree(root) et.write(out_F, encoding='UTF-8', xml_declaration=True)
#quit() root[0][1].text = str(3012) root[0][3].text = 'testtest' for child in root: print(child.tag, child.attrib) for ch2 in child: if ch2.text is not None: print('TEXT EL', ch2.tag, ':', ch2.text) else: print('ATTR EL', ch2.tag, ':', ch2.attrib) print(root[0][1].tag + ':', root[0][1].text) tree = ET.ElementTree(root) tree.write('xmlfile.xml') a = ET.Element('a') b = ET.SubElement(a,'b') b.text = 'Hello' tree = ET.ElementTree(a) tree.write('xmlxml.xml') ET.dump(a)
def _printXML(self, xml): """ Pretty Print XML, for internal debug""" print("_printXML start") ET.dump(xml)
from xml.etree import ElementTree as ET import csv import os def _add_elem(parent, tag, text='\n', **kwargs): elem = ET.Element(tag, **kwargs) elem.text, elem.tail = text, text if parent is not None: parent.append(elem) return elem root = ET.Element('contact_list', status='Private', company='Example, Inc') root.text, root.tail = '\n', '\n' with open(os.getcwd()+r'\data\example_data.csv') as f: for lname, fname, title, employment_type, email, phone in csv.reader(f): employee = _add_elem(root, 'employee') _add_elem(employee, 'full_name', f'{fname} {lname}') _add_elem(employee, 'job_title', title) _add_elem(employee, 'job_type', employment_type) _add_elem(employee, 'work_email', email) _add_elem(employee, 'work_phone', phone) ET.dump(root)
import requests import xml.etree.ElementTree as xmltree url = "http://cloud.culture.tw/frontsite/trans/emapOpenDataAction.do?\ method=exportEmapXML&typeId=A&classifyId=1.1" result = requests.get(url) element = xmltree.fromstring(result.text) print(xmltree.dump(element)) for item in element.findall('./emapItem/emap/Info'): print(item.attrib['name'], item.attrib['level'], item.attrib['cityName'], item.attrib['address'])