class dict2xml(object): def __init__(self, structure): self.doc = Document() if len(structure) == 1: rootName = unicode(structure.keys()[0]) self.root = self.doc.createElement(rootName) self.doc.appendChild(self.root) self.build(self.root, structure[rootName]) def build(self, father, structure): if type(structure) == dict: for k in structure: tag = self.doc.createElement(k) father.appendChild(tag) self.build(tag, structure[k]) elif type(structure) == list: grandFather = father.parentNode tagName = father.tagName grandFather.removeChild(father) for l in structure: tag = self.doc.createElement(tagName) self.build(tag, l) grandFather.appendChild(tag) else: data = structure tag = self.doc.createTextNode(data) father.appendChild(tag) def display(self): print self.doc.toprettyxml(indent=" ")
def test_handle_repr_set(self): ''' ''' emotionml = Document() repset_name = 'dimension-set' repset = Representation(name='fear', representation='dimension') emotionml = handle_repr_set(repset_name, repset, emotionml) print emotionml.toprettyxml()
def __repr__(self): if (self.menu_id == None): xml = Document() xml_menu = xml.createElement("menu") x_no_menu = xml.createTextNode("No menu Loaded") xml_menu.appendChild(x_no_menu) xml.appendChild(xml_menu) return xml.toprettyxml(indent=" ") else : xml = Document() xml_menu = xml.createElement("menu") xml.appendChild(xml_menu) xml_menu_id = xml.createElement("id") x_menu_id = xml.createTextNode(str(self.menu_id)) xml_menu_id.appendChild(x_menu_id) xml_menu.appendChild(xml_menu_id) xml_menu_name = xml.createElement("name") x_menu_name = xml.createTextNode(str(self.menu_name)) xml_menu_name.appendChild(x_menu_name) xml_menu.appendChild(xml_menu_name) return xml.toprettyxml(indent=" ")
def genXML( instlist, ssinfo ): """Write Ingres instance data out in XML.""" # Create document for instance data and base element instdoc = Document() pkginfo = instdoc.createElement( "IngresPackageInfo" ) instdoc.appendChild( pkginfo ) # Saveset element saveset = instdoc.createElement("saveset") saveset.setAttribute( "product", product ) pkginfo.appendChild( saveset ) # Instances element instances = instdoc.createElement("instances") pkginfo.appendChild( instances ) # write out saveset info first genXMLTagsFromDict( instdoc, saveset, ssinfo ) # loop through the list of instances and add to DOM for inst in instlist: # Create instance instance = instdoc.createElement("instance") instances.appendChild( instance ) # now iterate over all the keys using the keys as XML genXMLTagsFromDict( instdoc, instance, inst ) if pprint: print instdoc.toprettyxml(indent=" ") return writeXML( outfile, instdoc )
def createXMLFile(): # Create the minidom document doc = Document() # Create the <top> base element top = doc.createElement("top") doc.appendChild(top) detectorSet = doc.createElement("t1_detector_set") detectorSet.setAttribute("id", "1") top.appendChild(detectorSet) for (arm, planes) in deadChannelsMap.items(): #for every arm add arm tag and its childs armElement = doc.createElement("t1_arm") armElement.setAttribute("id", arm) for (plane, chambers) in planes.items(): #for every plane add plane tag planeElement = doc.createElement("t1_plane") planeElement.setAttribute("id", plane) for (chamber, channelTypes) in chambers.items(): #for every chamber add chamber tag chamberElement = doc.createElement("t1_csc") chamberElement.setAttribute("id", chamber) for (channelType, channels) in channelTypes.items(): #for every channelType add plane tag channelTypeElement = doc.createElement("t1_channel_type") channelTypeElement.setAttribute("id", channelType) channelTypeElement.setAttribute("fullmask", "no") for (channel, trash) in channels.items(): #for every channel write tag channelElement = doc.createElement("channel"); channelElement.setAttribute("id", channel) channelTypeElement.appendChild(channelElement) chamberElement.appendChild(channelTypeElement) planeElement.appendChild(chamberElement) armElement.appendChild(planeElement) detectorSet.appendChild(armElement) print doc.toprettyxml(indent=" ") #print XML document in readable way
def BuildXMl(url): xbmc.executebuiltin("XBMC.Notification(Please Wait!,Refreshing Movie List,5000)") link = GetContent(url) newlink = ''.join(link.splitlines()).replace('\t','') newlink=newlink[newlink.find('<b>Scroll Down To View Full Movie List</b>'):len(newlink)] mydoc=Document() mlist = mydoc.createElement("movielist") mydoc.appendChild(mlist) match=re.compile('<strong>(.+?)</strong><br /><img src="(.+?)" width="75" height="75" align="center" />').findall(newlink) maxcountry = len(match) for i in range(maxcountry): (vCountry,vImg)=match[i] xCountry= mydoc.createElement("country") mlist.appendChild(xCountry) xCountry.setAttribute("thumb", vImg) xCountry.setAttribute("name", vCountry) startlen = newlink.find('<strong>'+vCountry+'</strong><br /><img') endlen = 0 if(i < maxcountry-1): (vCountry2,vImg2)=match[i+1] endlen=newlink.find('<strong>'+vCountry2+'</strong><br /><img') else: endlen = len(newlink) ParseXML(startlen,endlen,newlink, mydoc,xCountry) print mydoc.toprettyxml() f = open(filename, 'w');f.write(mydoc.toprettyxml());f.close()
def main(): # Create the minidom document doc=Document() # Create the <wml> base element svg = doc.createElement("svg") svg.setAttribute('version', '1.1') svg.setAttribute('baseProfile', 'full') svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg') svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink') svg.setAttribute('xmlns:ev', 'http://www.w3.org/2001/xml-events') svg.setAttribute('height', '400px') svg.setAttribute('width', '400px') doc.appendChild(svg) rect = doc.createElement('rect') rect.setAttribute( 'x', '0' ) rect.setAttribute( 'y', '0' ) rect.setAttribute( 'width', '200' ) rect.setAttribute( 'height', '200' ) rect.setAttribute( 'fill', 'none' ) rect.setAttribute( 'stroke', 'black' ) rect.setAttribute( 'stroke-width', '5px' ) rect.setAttribute( 'stroke-opacity', '0.5' ) svg.appendChild( rect ) print doc.toprettyxml(indent=" ")
def writeDocument(files,outputFileName): xmlDoc = Document() root = xmlDoc.createElement('GizintaPlaylist') xmlDoc.appendChild(root) root.setAttribute("logTableName",'gzLog') root.setAttribute("errorTableName",'gzError') root.setAttribute("fileExtension",'.dwg') root.setAttribute("xmlns:gizinta",'http://gizinta.com') for fname in files: fElem = xmlDoc.createElement("File") root.appendChild(fElem) nodeText = xmlDoc.createTextNode(fname) fElem.appendChild(nodeText) try: xmlStr = xmlDoc.toprettyxml() uglyXml = xmlDoc.toprettyxml(indent=' ') text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL) prettyXml = text_re.sub('>\g<1></', uglyXml) fHandle = open(outputFileName, 'w') fHandle.write(prettyXml) fHandle.close() except: gzSupport.showTraceback() xmlStr ="" return xmlStr
def createfilexml(self): global Mpath,Magent homep=Mpath if not os.path.isdir(homep+"/xssalertdefault"): os.mkdir(homep+"/xssalertdefault") f1=open(homep+"/xssalertdefault/payload.xml","w") f2=open(homep+"/xssalertdefault/header.xml","w") f3=open(homep+"/xssalertdefault/url.xml","w") dom1=Document() x=dom1.createElement("xssalert") dom1.appendChild(x) i=0 while i < 2: xa=dom1.createElement("xssalertvector") x.appendChild(xa) vr=dom1.createElement("vector") xa.appendChild(vr) testvr=dom1.createCDATASection("??") vr.appendChild(testvr) i=i+1 f1.write(dom1.toprettyxml(" ")) dom2=Document() y=dom2.createElement("xssalert") dom2.appendChild(y) i=0 while i<2: xb=dom2.createElement("xssalertheader") y.appendChild(xb) hr=dom2.createElement("header") xb.appendChild(hr) testhr=dom2.createCDATASection("??") hr.appendChild(testhr) i=i+1 f2.write(dom2.toprettyxml(" ")) dom3=Document() z=dom3.createElement("xssalert") dom3.appendChild(z) i=0 while i<2: xc=dom3.createElement("xssalerturl") z.appendChild(xc) ur=dom3.createElement("url") xc.appendChild(ur) testhr=dom3.createCDATASection("??") ur.appendChild(testhr) i=i+1 f3.write(dom3.toprettyxml(" ")) f1.close() f2.close() f3.close() self.file_create_alert.setText("Default directory with XML files Created in '"+homep+"' \n Replace '??' with your text")
def test_add_section_to_xml(self): xml = Document() toolbox = xml.createElement('toolbox') xml.appendChild(toolbox) add_section_to_xml("Section 1", ['script1.py', 'script2.py'], xml) self.assertEqual(xml.toprettyxml(indent='\t'), exp_add_sect) add_section_to_xml("Section 2", [], xml) self.assertEqual(xml.toprettyxml(indent='\t'), exp_add_void_sect)
def ancientOne(self): """" This will save all the Ancient One's xml data. """ doc = Document() #create the root level element root = doc.createElement("ancientone") #create first level elements (sube elements to root element) name = doc.createElement("name") title = doc.createElement("title") combatRating = doc.createElement("combatrating") doomTrack = doc.createElement("doomtrack") worshipers = doc.createElement("worshipers") defence = doc.createElement("defence") power = doc.createElement("power") attack = doc.createElement("attack") #create second level elements. Will attack to first level elements. worshipersDescription = doc.createElement("description") worshipersType = doc.createElement("type") worshipersMods = doc.createElement("mods") powerName = doc.createElement("name") powerDescription = doc.createElement("description") #time to put the basic structure together doc.appendChild(root) root.appendChild(name) root.appendChild(title) root.appendChild(combatRating) root.appendChild(doomTrack) root.appendChild(worshipers) root.appendChild(defence) root.appendChild(power) root.appendChild(attack) worshipers.appendChild(worshipersDescription) worshipers.appendChild(worshipersMods) worshipers.appendChild(worshipersType) power.appendChild(powerName) power.appendChild(powerDescription) #now that the structure is all there, we need to get the values. nameTxt = doc.createTextNode(str(self.txtAncientOneName.displayText())) titleTxt = doc.createTextNode(str(self.txtAncientOneTitle.displayText())) combatRatingTxt = doc.createTextNode(str(self.txtAncientOneCombatRating.displayText())) name.appendChild(nameTxt) print doc.toprettyxml(indent=" ")
class dict2xml(object): def __init__(self, structure): if len(structure) == 1: self.doc = Document() rootName = str(structure.keys()[0]) self.root = self.doc.createElement(rootName) self.doc.appendChild(self.root) self.build(self.root, structure[rootName]) def build(self, father, structure): if type(structure) == dict: for k in structure: if "/" in k: tag = self.doc.createElement("location") tag.setAttribute("path", k) father.appendChild(tag) self.build(tag, structure[k]) else: tag = self.doc.createElement(k) father.appendChild(tag) self.build(tag, structure[k]) elif type(structure) == list: grandFather = father.parentNode tagName = father.tagName grandFather.removeChild(father) for l in structure: #tag = self.doc.createElement(tagName) self.build(father, l) grandFather.appendChild(father) elif isinstance(structure, MovieInfo): tag = self.doc.createElement("movie") tag.setAttribute("name", structure.name) tag.setAttribute("path", structure.path) tag.setAttribute("type", str(structure.type)) tag.setAttribute("flags", str(structure.flags)) father.appendChild(tag) else: data = str(structure) tag = self.doc.createTextNode(data) father.appendChild(tag) def display(self): print self.doc.toprettyxml(indent=" ") def write(self, file_name): try: xmlstr = self.doc.toprettyxml() #self.doc.toxml('utf-8') f = open(file_name, 'w') f.write(xmlstr) f.close() except: printStackTrace()
def generate_reports(self, test_runner): """ Generates the XML reports to a given XMLTestRunner object. """ from xml.dom.minidom import Document all_results = self._get_info_by_testcase() outputHandledAsString = \ isinstance(test_runner.output, six.string_types) if (outputHandledAsString and not os.path.exists(test_runner.output)): os.makedirs(test_runner.output) if not outputHandledAsString: doc = Document() testsuite = doc.createElement('testsuites') doc.appendChild(testsuite) parentElement = testsuite for suite, tests in all_results.items(): if outputHandledAsString: doc = Document() parentElement = doc suite_name = suite if test_runner.outsuffix: # not checking with 'is not None', empty means no suffix. suite_name = '%s-%s' % (suite, test_runner.outsuffix) # Build the XML file testsuite = _XMLTestResult._report_testsuite( suite_name, tests, doc, parentElement, self.properties ) if outputHandledAsString: xml_content = doc.toprettyxml( indent='\t', encoding=test_runner.encoding ) filename = path.join( test_runner.output, 'TEST-%s.xml' % suite_name) with open(filename, 'wb') as report_file: report_file.write(xml_content) if self.showAll: self.stream.writeln('Generated XML report: {}'.format(filename)) if not outputHandledAsString: # Assume that test_runner.output is a stream xml_content = doc.toprettyxml( indent='\t', encoding=test_runner.encoding ) test_runner.output.write(xml_content)
def dump_xml(self): """Dump scenario information in XML format, something like: <$job_partition> <nodes> <node>node1</node> <node>node2</node> </nodes> <config> <node>$firstnode</node> <ipaddress>$iprin</ipaddress> <session>$rfbport</session> <password>$mdp</password> </config> <enddatetime>$daylimit</enddatetime> <pid>$jobid</pid> </$job_partition> """ doc = Document() root = doc.createElement(self.conf.cluster_partition) doc.appendChild(root) nodes = doc.createElement('nodes') root.appendChild(nodes) for nodename in self.job.nodes: node = doc.createElement('node') node.appendChild(doc.createTextNode(nodename)) nodes.appendChild(node) config = doc.createElement('config') config_elmt = doc.createElement('node') config_elmt.appendChild(doc.createTextNode(self.job.firstnode)) config.appendChild(config_elmt) config_elmt = doc.createElement('ipaddress') config_elmt.appendChild(doc.createTextNode(self.rinip)) config.appendChild(config_elmt) config_elmt = doc.createElement('session') config_elmt.appendChild(doc.createTextNode(str(self.rfbport))) config.appendChild(config_elmt) config_elmt = doc.createElement('password') config_elmt.appendChild(doc.createTextNode(self.password)) config.appendChild(config_elmt) root.appendChild(config) enddatetime = doc.createElement('enddatetime') enddatetime.appendChild(doc.createTextNode(self.job.end.isoformat())) root.appendChild(enddatetime) pid = doc.createElement('pid') pid.appendChild(doc.createTextNode(str(self.job.jobid))) root.appendChild(pid) print doc.toprettyxml() sys.stdout.flush() # force flush to avoid buffering
def sms_messages_to_xml(xml_dir, sms_list): _adel_log.log("############ XML OUTPUT GENERATION -> SMS MESSAGES ############ \n", 2) # Create the minidom document doc = Document() xml = doc.createElement("SMS_Messages") doc.appendChild(xml) for i in range(0, len(sms_list)): # Create the <SMS_Message> element sms_message = doc.createElement("SMS_Message") xml.appendChild(sms_message) id = doc.createElement("id") sms_message.appendChild(id) id_text = doc.createTextNode(sms_list[i][0]) id.appendChild(id_text) thread_id = doc.createElement("thread_id") sms_message.appendChild(thread_id) thread_id_text = doc.createTextNode(sms_list[i][1]) thread_id.appendChild(thread_id_text) number = doc.createElement("number") sms_message.appendChild(number) number_text = doc.createTextNode(sms_list[i][2]) number.appendChild(number_text) person = doc.createElement("person") sms_message.appendChild(person) person_text = doc.createTextNode(sms_list[i][3]) person.appendChild(person_text) date = doc.createElement("date") sms_message.appendChild(date) date_text = doc.createTextNode(sms_list[i][4]) date.appendChild(date_text) read = doc.createElement("read") sms_message.appendChild(read) read_text = doc.createTextNode(sms_list[i][5]) read.appendChild(read_text) type = doc.createElement("type") sms_message.appendChild(type) type_text = doc.createTextNode(sms_list[i][6]) type.appendChild(type_text) subject = doc.createElement("subject") sms_message.appendChild(subject) subject_text = doc.createTextNode(sms_list[i][7]) subject.appendChild(subject_text) body = doc.createElement("body") sms_message.appendChild(body) body_text = doc.createTextNode(sms_list[i][8]) body.appendChild(body_text) # Print our newly created XML files to Log _adel_log.log(make_pretty_xml(doc.toprettyxml(indent=" ", encoding="UTF-8")), 3) # create xml file xml_sms_messages = open(xml_dir + "/sms_Messages.xml", "a+") xml_sms_messages.write(make_pretty_xml(doc.toprettyxml(indent=" ", encoding="UTF-8"))) xml_sms_messages.close() _adel_log.log("xmlParser: ----> sms_Messages.xml created!", 4)
def calendar_to_xml(xml_dir, calendar_list): _adel_log.log("############ XML OUTPUT GENERATION -> CALENDAR ENTRIES ############ \n", 2) # Create the minidom document doc = Document() xml = doc.createElement("Calendar_Entries") doc.appendChild(xml) for i in range(0, len(calendar_list)): # Create the <Calendar_Entry> element calendar_entry = doc.createElement("Calendar_Entry") xml.appendChild(calendar_entry) id = doc.createElement("id") calendar_entry.appendChild(id) id_text = doc.createTextNode(calendar_list[i][0]) id.appendChild(id_text) calendarName = doc.createElement("calendarName") calendar_entry.appendChild(calendarName) calendarName_text = doc.createTextNode(calendar_list[i][1]) calendarName.appendChild(calendarName_text) title = doc.createElement("title") calendar_entry.appendChild(title) title_text = doc.createTextNode(calendar_list[i][2]) title.appendChild(title_text) eventLocation = doc.createElement("eventLocation") calendar_entry.appendChild(eventLocation) event_location_text = doc.createTextNode(calendar_list[i][3]) eventLocation.appendChild(event_location_text) description = doc.createElement("description") calendar_entry.appendChild(description) description_text = doc.createTextNode(calendar_list[i][4]) description.appendChild(description_text) all_day = doc.createElement("all_day") calendar_entry.appendChild(all_day) allDay_text = doc.createTextNode(calendar_list[i][5]) all_day.appendChild(allDay_text) start = doc.createElement("start") calendar_entry.appendChild(start) start_text = doc.createTextNode(calendar_list[i][6]) start.appendChild(start_text) end = doc.createElement("end") calendar_entry.appendChild(end) end_text = doc.createTextNode(calendar_list[i][7]) end.appendChild(end_text) has_alarm = doc.createElement("has_alarm") calendar_entry.appendChild(has_alarm) has_alarm_text = doc.createTextNode(calendar_list[i][8]) has_alarm.appendChild(has_alarm_text) # Print our newly created XML files to Log _adel_log.log(make_pretty_xml(doc.toprettyxml(indent=" ", encoding="UTF-8")), 3) # create xml file xml_calendar = open(xml_dir + "/calendar.xml", "a+") xml_calendar.write(make_pretty_xml(doc.toprettyxml(indent=" ", encoding="UTF-8"))) xml_calendar.close() _adel_log.log("xmlParser: ----> calendar.xml created!", 4)
def test_update_tool_conf_xml(self): xml = Document() toolbox = xml.createElement('toolbox') xml.appendChild(toolbox) section_dict = {"Section 1": ['script1.py', 'script2.py'], "Section 2": ['script3.py']} update_tool_conf_xml(xml, section_dict) self.assertEqual(xml.toprettyxml(indent='\t'), exp_update_1) section_dict["Section 3"] = ['script4.py', 'script5.py'] update_tool_conf_xml(xml, section_dict) self.assertEqual(xml.toprettyxml(indent='\t'), exp_update_2)
def test_filetree(): testpath = os.path.abspath('..') doc = Document() doc.appendChild(makenode(doc,testpath)) print doc.toprettyxml() print '' print '' dict = filedict(testpath) jsondict = jsonpickle.encode(dict) print 'json = ',json.dumps(jsondict,sort_keys=False,indent=4)
class XmlBuilder: ## Konstruktor def __init__(self): self.doc = Document() ## Funkcja tworzaca nowego node'a # @param node_name: Nazwa tworzonego node'a # @param parent_node: Rodzic tworzonego node'a - parametr nieobowiazkowy # @param value: Wartosc tworzonego node'a - parametr nieobowiazkowy # @param with_attribs: Slownik atrybutow tworzonego node'a - parametr nieobowiazkowy # @return: def createNode(self, node_name, parent_node = '', value = '', with_attribs = {}): node = self.doc.createElement(node_name) if parent_node == '': # Utworzenie rodzica created_node = self.doc.appendChild(node) else: # Utworzenie dziecka created_node = parent_node.appendChild(node) if value != '': text_node = self.doc.createTextNode(value) node.appendChild(text_node) if with_attribs != {}: for key, value in with_attribs.items(): self.setAttribute(created_node, key, value) return created_node ## Funkcja dodajaca atrybut do zadanego node'a # @param node: Node, do ktorego ma zostac dodany atrybut # @param key: Nazwa atrybutu # @param value: Wartosc atrybutu def setAttribute(self, node, key, value): node.setAttribute(key, value) ## Funkcja zwracajaca aktualnie wygenerowanego XMLa # @return: Aktualnie zbudowany plik XML w postaci tekstowej def getXML(self): text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL) pretty_XML = text_re.sub('>\g<1></', self.doc.toprettyxml(encoding="utf-8", indent=" ")) pretty_XML = pretty_XML.replace(""", "\"") return pretty_XML ## Funkcja zapisuje aktualnie wygenerowanego XMLa do podanego sciazka pliku # @param file_name: Sciezka do pliku, gdzie ma zostac zapisany plik XML def saveXML(self, file_name): xml_file = open(file_name, "w") text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL) pretty_XML = text_re.sub('>\g<1></', self.doc.toprettyxml(encoding="utf-8", indent=" ")) pretty_XML = pretty_XML.replace(""", "\"") xml_file.write(str(pretty_XML)) xml_file.close()
def OutputXML(self,id,idlist,titlelist,geolist,refinelist): fname = gconfig.outputdir + '/' + '%s.xml' % id setid = set(idlist) setgeo = set(geolist) - setid settitle = set(titlelist) - setid setrefinelist = set(refinelist) - setid sets = [setid,setgeo,settitle,setrefinelist] tmpinfo = ["query by ID","query by Geo - ID", "query by Title - ID"," Pruning and Refine"] doc = Document() query = doc.createElement("query") query.setAttribute("id",id) doc.appendChild(query) results = doc.createElement("PhotoSets") for tmpset,info in zip(sets,tmpinfo): photoset = doc.createElement("photoset") photoset.setAttribute('query',info) photoset.setAttribute('photoNum',str(len(tmpset))) for photo in tmpset: ph = doc.createElement("photo") ph.setAttribute('url', photo) photoset.appendChild(ph) results.appendChild(photoset) query.appendChild(results) f = open(fname, "w") f.write(doc.toprettyxml(encoding='UTF-8')) f.close()
def createBalanceSheetPDF(self): out = open("/tmp/balancesheet_"+str(self.id)+".xml","w") doc = Document() main = doc.createElement("koalixaccountingbalacesheet") calculationUnitName = doc.createElement("calculationUnitName") calculationUnitName.appendChild(doc.createTextNode(self.__unicode__())) main.appendChild(calculationUnitName) calculationUnitTo = doc.createElement("calculationUnitTo") calculationUnitTo.appendChild(doc.createTextNode(self.end.year.__str__())) main.appendChild(calculationUnitTo) calculationUnitFrom = doc.createElement("calculationUnitFrom") calculationUnitFrom.appendChild(doc.createTextNode(self.begin.year.__str__())) main.appendChild(calculationUnitFrom) accountNumber = doc.createElement("AccountNumber") accounts = Account.objects.all() for account in list(accounts) : currentValue = account.valueNow(self) if (currentValue != 0): currentAccountElement = doc.createElement("Account") accountNumber = doc.createElement("AccountNumber") accountNumber.appendChild(doc.createTextNode(account.accountNumber.__str__())) currentValueElement = doc.createElement("currentValue") currentValueElement.appendChild(doc.createTextNode(currentValue.__str__())) accountNameElement = doc.createElement("accountName") accountNameElement.appendChild(doc.createTextNode(account.title)) currentAccountElement.setAttribute("accountType", account.accountType.__str__()) currentAccountElement.appendChild(accountNumber) currentAccountElement.appendChild(accountNameElement) currentAccountElement.appendChild(currentValueElement) main.appendChild(currentAccountElement) doc.appendChild(main) out.write(doc.toprettyxml(indent=" ")) system("fop -c /var/www/koalixcrm/verasans.xml -xml /tmp/balancesheet_"+str(self.id)+".xml -xsl /var/www/koalixcrm/balancesheet.xsl -pdf /tmp/balancesheet_"+str(self.id)+".pdf") return "/tmp/balancesheet_"+str(self.id)+".pdf"
def write_xml_hypergraph(hypergraph): """ Return a string specifying the given hypergraph as a XML document. @type hypergraph: hypergraph @param hypergraph: Hypergraph. @rtype: string @return: String specifying the graph as a XML document. """ # Document root grxml = Document() grxmlr = grxml.createElement('hypergraph') grxml.appendChild(grxmlr) # Each node... nodes = hypergraph.nodes() hyperedges = hypergraph.get_hyperedges() for each_node in (nodes + hyperedges): if (each_node in nodes): node = grxml.createElement('node') else: node = grxml.createElement('hyperedge') node.setAttribute('id',str(each_node)) grxmlr.appendChild(node) # and its outgoing edge for each_edge in hypergraph.get_links(each_node): edge = grxml.createElement('link') edge.setAttribute('to',str(each_edge)) node.appendChild(edge) return grxml.toprettyxml()
def generate_reports(self, test_runner): "Generates the XML reports to a given XMLTestRunner object." from xml.dom.minidom import Document all_results = self._get_info_by_testcase() if type(test_runner.output) == str and not \ os.path.exists(test_runner.output): os.makedirs(test_runner.output) for suite, tests in all_results.items(): doc = Document() # Build the XML file testsuite = _XMLTestResult._report_testsuite(suite, tests, doc) for test in tests: _XMLTestResult._report_testcase(suite, test, testsuite, doc) _XMLTestResult._report_output(suite, tests, test_runner, testsuite, doc) xml_content = doc.toprettyxml(indent='\t') if type(test_runner.output) is str: report_file = open(os.path.join(test_runner.output, '%s.xml' % (suite,)), 'w') try: report_file.write(xml_content) finally: report_file.close() else: # Assume that test_runner.output is a stream test_runner.output.write(xml_content)
def generate_reports(self, test_runner): "Generates the XML reports to a given XMLTestRunner object." from xml.dom.minidom import Document all_results = self._get_info_by_testcase() if type(test_runner.output) == str and not \ os.path.exists(test_runner.output): os.makedirs(test_runner.output) for suite, tests in all_results.items(): doc = Document() # Build the XML file testsuite = _XMLTestResult._report_testsuite(suite, tests, doc) stdout, stderr = [], [] for test in tests: _XMLTestResult._report_testcase(suite, test, testsuite, doc) if test.stdout: stdout.extend(['*****************', test.get_description(), test.stdout]) if test.stderr: stderr.extend(['*****************', test.get_description(), test.stderr]) _XMLTestResult._report_output(test_runner, testsuite, doc, '\n'.join(stdout), '\n'.join(stderr)) xml_content = doc.toprettyxml(indent='\t') if type(test_runner.output) is str: report_file = open('%s%sTEST-%s.xml' % \ (test_runner.output, os.sep, suite), 'w') try: report_file.write(xml_content) finally: report_file.close() else: # Assume that test_runner.output is a stream test_runner.output.write(xml_content)
def save(self, filename): # ... create xml doc from xml.dom.minidom import Document # Create the minidom document doc = Document() # Create the <caid> base element rootElt = doc.createElement("field") # set camera attributs # eye = self.viewer.lookAt.GetEye() # rootElt.setAttribute("eye", str(eye)) doc.appendChild(rootElt) from caid.io import XML io = XML() # ... geometry geoElt = doc.createElement("geometry") geo = self.geometry doc = io.geotoxml(geo, doc, geoElt) rootElt.appendChild(geoElt) # ... geometry valuesElt = doc.createElement("values") values = self.values doc = io.geotoxml(values, doc, valuesElt) rootElt.appendChild(valuesElt) if filename is not None: f = open(filename, 'wr') s = doc.toprettyxml() f.write(s) f.close() else: print("No file was specified")
def txt_export(filepath): doc = Document() root = doc.createElement('data') doc.appendChild(root) for sce in bpy.data.scenes : #create a scene scene = doc.createElement('scene') scene.setAttribute('name', sce.name) root.appendChild(scene) for obj in sce.objects : if obj.type == 'FONT': #add object element object = doc.createElement('object') object.setAttribute('name', obj.name) txt_node = doc.createTextNode(obj.data.body) object.appendChild(txt_node) scene.appendChild(object) #write to a file file_handle = open(filepath,"wb") file_handle.write(bytes(doc.toprettyxml(indent='\t'), 'UTF-8')) file_handle.close()
def formXml(self): """Form the XML to be written to RssFeeds.xml""" #create the document doc = Document() #create root element rssfeedsTag = doc.createElement('rssfeeds') doc.appendChild(rssfeedsTag) #create comments c1Tag = doc.createComment('RSS feeds. To have multiple feeds, just add a feed to the set. You can also have multiple sets.') c2Tag = doc.createComment('To use different sets in your skin, each must be called from skin with a unique id.') rssfeedsTag.appendChild(c1Tag) rssfeedsTag.appendChild(c2Tag) for setNum in sorted(self.feedsList.keys()): #create sets setTag = doc.createElement('set') #create attributes setTag.setAttribute('id', self.feedsList[setNum]['attrs']['id']) #only write rtl tags if they've been explicitly set if 'rtl' in self.feedsList[setNum]['attrs']: setTag.setAttribute('rtl', self.feedsList[setNum]['attrs']['rtl']) rssfeedsTag.appendChild(setTag) #create feed elements for feed in self.feedsList[setNum]['feedslist']: feedTag = doc.createElement('feed') feedTag.setAttribute('updateinterval', feed['updateinterval']) feedUrl = doc.createTextNode(feed['url']) feedTag.appendChild(feedUrl) setTag.appendChild(feedTag) return doc.toprettyxml(indent = ' ', encoding = 'UTF-8')
def storeToFile(self, suffix=""): if not self.dataToStore: return doc = Document() results = doc.createElement("results") doc.appendChild(results) for a in self.dataToStore: item = doc.createElement("item") for k, d in a.items(): tag = doc.createElement(k) if k == "author": tag2 = doc.createElement("name") data = doc.createTextNode(d) tag2.appendChild(data) tag.appendChild(tag2) else: data = doc.createTextNode(" ".join(d.split())) tag.appendChild(data) item.appendChild(tag) results.appendChild(item) timestamp = time.strftime("%H%M%S_") f = open("output/" + timestamp + self.board + "_" + self.section + "_" + str(suffix) + ".xml", "w") f.write(doc.toprettyxml(indent=" ", encoding="utf-8")) f.close() self.dataToStore = []
def generate_reports(self, test_runner): "Generates the XML reports to a given XMLTestRunner object." from xml.dom.minidom import Document all_results = self._get_info_by_testcase() if isinstance(test_runner.output, basestring) and not \ os.path.exists(test_runner.output): os.makedirs(test_runner.output) for suite, tests in all_results.items(): doc = Document() # Build the XML file testsuite = _XMLTestResult._report_testsuite(suite, tests, doc) for test in tests: _XMLTestResult._report_testcase(suite, test, testsuite, doc) _XMLTestResult._report_output(test_runner, testsuite, doc) xml_content = doc.toprettyxml(indent='\t', encoding="utf-8") if type(test_runner.output) in (str, unicode): report_file = file('%s%sTEST-%s.xml' % \ (test_runner.output, os.sep, suite), 'w') try: report_file.write(xml_content) finally: report_file.close() else: # Assume that test_runner.output is a stream test_runner.output.write(xml_content)
def createDoc(path): file = open(path, "w") doc = Document() wml = doc.createElement("data") doc.appendChild(wml) file.write(doc.toprettyxml(indent=" ")) file.close()
def save_to_xml(save_path, file_name, img_shape, objects_axis, label_name, parseMode='parse_dota_rec'): """ param: save_path: new path for saving xml file im_height: image height im_width: image width object_axis: 坐标点(4×2) lable_name:从int解码出str(类别) parseMode: 选择解析为旋转框or水平框 return: (inplace) """ im_depth = 0 object_num = len(objects_axis) doc = Document() annotation = doc.createElement('annotation') doc.appendChild(annotation) folder = doc.createElement('folder') folder_name = doc.createTextNode('VOC2007') folder.appendChild(folder_name) annotation.appendChild(folder) filename = doc.createElement('filename') filename_name = doc.createTextNode(file_name) filename.appendChild(filename_name) annotation.appendChild(filename) source = doc.createElement('source') annotation.appendChild(source) database = doc.createElement('database') database.appendChild(doc.createTextNode('The VOC2007 Database')) source.appendChild(database) annotation_s = doc.createElement('annotation') annotation_s.appendChild(doc.createTextNode('PASCAL VOC2007')) source.appendChild(annotation_s) image = doc.createElement('image') image.appendChild(doc.createTextNode('flickr')) source.appendChild(image) flickrid = doc.createElement('flickrid') flickrid.appendChild(doc.createTextNode('322409915')) source.appendChild(flickrid) owner = doc.createElement('owner') annotation.appendChild(owner) flickrid_o = doc.createElement('flickrid') flickrid_o.appendChild(doc.createTextNode('knautia')) owner.appendChild(flickrid_o) name_o = doc.createElement('name') name_o.appendChild(doc.createTextNode('raymond')) owner.appendChild(name_o) size = doc.createElement('size') annotation.appendChild(size) im_width, im_height, im_depth = img_shape width = doc.createElement('width') width.appendChild(doc.createTextNode(str(im_width))) height = doc.createElement('height') height.appendChild(doc.createTextNode(str(im_height))) depth = doc.createElement('depth') depth.appendChild(doc.createTextNode(str(im_depth))) size.appendChild(width) size.appendChild(height) size.appendChild(depth) segmented = doc.createElement('segmented') segmented.appendChild(doc.createTextNode('0')) annotation.appendChild(segmented) for i in range(object_num): objects = doc.createElement('object') annotation.appendChild(objects) object_name = doc.createElement('name') object_name.appendChild( doc.createTextNode(label_name[int(objects_axis[i][-1])])) objects.appendChild(object_name) pose = doc.createElement('pose') pose.appendChild(doc.createTextNode('Unspecified')) objects.appendChild(pose) truncated = doc.createElement('truncated') truncated.appendChild(doc.createTextNode('1')) objects.appendChild(truncated) difficult = doc.createElement('difficult') difficult.appendChild(doc.createTextNode('0')) objects.appendChild(difficult) bndbox = doc.createElement('bndbox') objects.appendChild(bndbox) if parseMode == 'parse_dota_rec': xmin = doc.createElement('xmin') xmin.appendChild(doc.createTextNode(str((objects_axis[i][0])))) bndbox.appendChild(xmin) ymin = doc.createElement('ymin') ymin.appendChild(doc.createTextNode(str((objects_axis[i][1])))) bndbox.appendChild(ymin) xmax = doc.createElement('xmax') xmax.appendChild(doc.createTextNode(str((objects_axis[i][2])))) bndbox.appendChild(xmax) ymax = doc.createElement('ymax') ymax.appendChild(doc.createTextNode(str((objects_axis[i][3])))) bndbox.appendChild(ymax) else: x0 = doc.createElement('x0') x0.appendChild(doc.createTextNode(str((objects_axis[i][0])))) bndbox.appendChild(x0) y0 = doc.createElement('y0') y0.appendChild(doc.createTextNode(str((objects_axis[i][1])))) bndbox.appendChild(y0) x1 = doc.createElement('x1') x1.appendChild(doc.createTextNode(str((objects_axis[i][2])))) bndbox.appendChild(x1) y1 = doc.createElement('y1') y1.appendChild(doc.createTextNode(str((objects_axis[i][3])))) bndbox.appendChild(y1) x2 = doc.createElement('x2') x2.appendChild(doc.createTextNode(str((objects_axis[i][4])))) bndbox.appendChild(x2) y2 = doc.createElement('y2') y2.appendChild(doc.createTextNode(str((objects_axis[i][5])))) bndbox.appendChild(y2) x3 = doc.createElement('x3') x3.appendChild(doc.createTextNode(str((objects_axis[i][6])))) bndbox.appendChild(x3) y3 = doc.createElement('y3') y3.appendChild(doc.createTextNode(str((objects_axis[i][7])))) bndbox.appendChild(y3) f = open(save_path, 'w') f.write(doc.toprettyxml(indent='')) f.close()
genre = "" if (isinstance(value.BrowseNode, list)): for browseNode in value.BrowseNode: genre = genre + browseNode.BrowseName + "; " else: genre = value.BrowseNode.BrowseName fieldElement = doc.createElement("field") fieldElement.setAttribute("name", "genre") textElement = doc.createTextNode(genre) fieldElement.appendChild(textElement) bookElement.appendChild(fieldElement) else: fieldElement = doc.createElement("field") fieldElement.setAttribute("name", name) textElement = doc.createTextNode(value) fieldElement.appendChild(textElement) bookElement.appendChild(fieldElement) collection.appendChild(bookElement) print doc.toprettyxml(encoding="UTF-8", indent=" ") sys.stdout.flush()
def create_igv_session(genome, uuids, is_file_uuid=False): """ Creates session file for selected file uuids, returns newly created filestore uuid :param is_file_uuid: :param genome: Genome to be used in session file i.e. hg18, dm3 :type genome: string. :param uuids: Array of UUIDs to be used :type uuids: array. :param uuids: Host URL i.e. 127.0.0.1:8000 :type uuids: string """ # Create IGV Session file and put into Filestore """ http://www.postneo.com/projects/pyxml/ <?xml version="1.0" encoding="UTF-8"?> <Global genome="hg18" locus="EGFR" version="3"> <Resources> <Resource name="RNA Genes" path="http://www.broadinstitute.org/igvdata/tcga/gbm/GBM_batch1-8_level3_exp.txt.recentered.080820.gct.tdf"/> <Resource name="RNA Genes" path="http://www.broadinstitute.org/igvdata/annotations/hg18/rna_genes.bed"/> <Resource name="sno/miRNA" path="http://www.broadinstitute.org/igvdata/tcga/gbm/Sample_info.txt"/> </Resources> </Global> """ logger.debug("visualization_manager.create_igv_session called") # Create the minidom document doc = Document() # Create the <wml> base element xml = doc.createElement("Global") xml.setAttribute("genome", genome) xml.setAttribute("locus", "All") xml.setAttribute("version", "4") doc.appendChild(xml) # Add Resources xml_resources = doc.createElement("Resources") xml.appendChild(xml_resources) # get paths to url for samp in uuids: # gets filestore item curr_name, curr_url = get_file_name(samp, is_file_uuid=is_file_uuid) logger.debug('New resource: ' + curr_name + ' - ' + curr_url) # What to do if fs does not exist? if curr_name: # creates Resource element res = doc.createElement("Resource") res.setAttribute("name", curr_name) res.setAttribute("path", curr_url) xml_resources.appendChild(res) # Creating temp file to enter into file_store tempfilename = tempfile.NamedTemporaryFile(delete=False) tempfilename.write(doc.toprettyxml(indent=" ")) tempfilename.close() # getting file_store_uuid filestore_uuid = create(tempfilename.name, filetype="xml") filestore_item = import_file(filestore_uuid, refresh=True) # file to rename temp_name = filestore_item.datafile.name.split('/') temp_name = temp_name[len(temp_name) - 1] + '.xml' # rename file by way of file_store filestore_item = rename(filestore_uuid, temp_name) # delete temp file os.unlink(tempfilename.name) # Url for session file fs_url = get_full_url(filestore_item.get_datafile_url()) # IGV url for automatic launch of Java Webstart igv_url = "http://www.broadinstitute.org/igv/projects/current/igv.php" \ "?sessionURL=" + fs_url return igv_url
class XMLWriter(object): ''' classdocs ''' def __init__(self, doc_name=''): ''' Constructor ''' self.docname = doc_name self.out_doc = Document() self.out_doc.version = "1.0" self.out_doc.doctype = "xml" self.out_doc.standalone = "yes" self.sph_element = self.out_doc.createElement('SPHModel') self.sph_element.setAttribute('zMin',str(Const.zmin)) self.sph_element.setAttribute('zMax',str(Const.zmax)) self.sph_element.setAttribute('xMin',str(Const.xmin)) self.sph_element.setAttribute('xMax',str(Const.xmax)) self.sph_element.setAttribute('yMin',str(Const.ymin)) self.sph_element.setAttribute('yMax',str(Const.ymax)) self.sph_element.setAttribute('xmlns',"http://www.example.org/SPHSchema") self.out_doc.appendChild(self.sph_element) def add_particle(self, particle): particle_ellement = self.out_doc.createElement('particles') particle_ellement.setAttribute('mass', str(Const.mass)) p_pos_ellement = self.out_doc.createElement('positionVector') p_pos_ellement.setAttribute('p', str(particle.type)) p_pos_ellement.setAttribute('z', str(particle.position.z)) p_pos_ellement.setAttribute('y', str(particle.position.y)) p_pos_ellement.setAttribute('x', str(particle.position.x)) p_vel_ellement = self.out_doc.createElement('velocityVector') p_vel_ellement.setAttribute('p', str(particle.type)) p_vel_ellement.setAttribute('z', str(particle.velocity.z)) p_vel_ellement.setAttribute('y', str(particle.velocity.y)) p_vel_ellement.setAttribute('x', str(particle.velocity.x)) particle_ellement.appendChild(p_pos_ellement) particle_ellement.appendChild(p_vel_ellement) self.sph_element.appendChild(particle_ellement) del particle_ellement def add_connection(self, connection): connection_ellement = self.out_doc.createElement('connections') jd_ellement = self.out_doc.createElement('p1') ptext = self.out_doc.createTextNode(str(connection.particle_j)) jd_ellement.appendChild(ptext) distance_ellemtn = self.out_doc.createElement('distance') ptext = self.out_doc.createTextNode(str(connection.r_ij)) distance_ellemtn.appendChild(ptext) val1_ellemnt = self.out_doc.createElement('mysteryValue') ptext = self.out_doc.createTextNode(str(connection.val1)) val1_ellemnt.appendChild(ptext) connection_ellement.appendChild(jd_ellement) connection_ellement.appendChild(distance_ellemtn) connection_ellement.appendChild(val1_ellemnt) self.sph_element.appendChild(connection_ellement) def printtoFile(self): try: f = open('./configurations/' + self.docname + '.xml', 'w') f.write(self.out_doc.toprettyxml(encoding='utf-8')) f.close() print 'Configuration was save in file % s in flder configuration', self.docname + '.xml' except IOError as ex: print 'Configuration wasn''t saved because : %s' % ex.strerror
def CreateImgXMLFileMask(im_annos, im_name, im_size, f, xml_folder, data_type, mask_folder, id_to_id, mask_type='.png', img_type='.jpg'): doc = Document() annotation = doc.createElement('annotation') doc.appendChild(annotation) folder = doc.createElement('folder') folder_text = doc.createTextNode(data_type) folder.appendChild(folder_text) annotation.appendChild(folder) filename = doc.createElement('filename') filename_text = doc.createTextNode(im_name+img_type) filename.appendChild(filename_text) annotation.appendChild(filename) size = doc.createElement('size') width = doc.createElement('width') width_value = doc.createTextNode(str(im_size[1])) width.appendChild(width_value) size.appendChild(width) height = doc.createElement('height') height_value = doc.createTextNode(str(im_size[0])) height.appendChild(height_value) size.appendChild(height) depth = doc.createElement('depth') if len(im_size) == 3: depth_value = doc.createTextNode(str(im_size[2])) elif len(im_size) == 2: depth_value = doc.createTextNode(str(1)) else: assert False, "invalid image size." depth.appendChild(depth_value) size.appendChild(depth) annotation.appendChild(size) for i in range(len(im_annos)): anno = im_annos[i] instance = doc.createElement('object') im_category_id = anno['category_id'] im_instance_id = i + 1 category_id = doc.createElement('category_id') category_id_value = doc.createTextNode(str(id_to_id[im_category_id])) category_id.appendChild(category_id_value) instance.appendChild(category_id) instance_id = doc.createElement('instance_id') instance_id_value = doc.createTextNode(str(im_instance_id)) instance_id.appendChild(instance_id_value) instance.appendChild(instance_id) iscrowd = anno['iscrowd'] difficult = doc.createElement('difficult') difficult_value = doc.createTextNode(str(iscrowd)) difficult.appendChild(difficult_value) instance.appendChild(difficult) bndbox = doc.createElement('bndbox') bbox = anno['bbox'] im_xmin = int(np.floor(bbox[0])) im_ymin = int(np.floor(bbox[1])) im_width = np.ceil(bbox[2]) im_height = np.ceil(bbox[3]) im_xmax = int(im_xmin + im_width) im_ymax = int(im_ymin + im_height) xmin = doc.createElement('xmin') xmin_value = doc.createTextNode(str(im_xmin)) xmin.appendChild(xmin_value) bndbox.appendChild(xmin) ymin = doc.createElement('ymin') ymin_value = doc.createTextNode(str(im_ymin)) ymin.appendChild(ymin_value) bndbox.appendChild(ymin) xmax = doc.createElement('xmax') xmax_value = doc.createTextNode(str(im_xmax)) xmax.appendChild(xmax_value) bndbox.appendChild(xmax) ymax = doc.createElement('ymax') ymax_value = doc.createTextNode(str(im_ymax)) ymax.appendChild(ymax_value) bndbox.appendChild(ymax) instance.appendChild(bndbox) annotation.appendChild(instance) binary_mask = coco.annToMask(anno).astype(np.uint8) imsave(mask_folder + im_name + '_' + str(im_instance_id) + mask_type, binary_mask) with open(xml_folder + im_name + '.xml', 'w') as f_xml: f_xml.write(doc.toprettyxml(indent='\t', encoding='utf-8')) f.write(dataType+'/'+im_name+img_type + ' ' + 'instance/'+dataType+'/'+im_name + ' ' + 'xml/'+dataType+'/'+im_name+'.xml\n') print im_name
def WriteLog(self, project): const_startend_time_format = "%04d%02d%02dT%02d%02d%02d" prj = project.strip() key_command = prj doc = Document() eleDoc = doc.createElement('Projects') eleParent = doc.createElement(self.projectName) if (self.start_time != None): startLogNode = doc.createElement(const_start_time_node) time_log_lebel = const_startend_time_format % (self.start_time.year, self.start_time.month, self.start_time.day, \ self.start_time.hour, self.start_time.minute, self.start_time.second) startLogNode.appendChild(doc.createTextNode(time_log_lebel)) eleParent.appendChild(startLogNode) #add start-time, end-time and the duration under each project node. end_time = datetime.now() if (self.end_time != None): end_time = self.end_time endLogNode = doc.createElement('EndTime') time_log_lebel = const_startend_time_format % (end_time.year, end_time.month, end_time.day, \ end_time.hour, end_time.minute, end_time.second) endLogNode.appendChild(doc.createTextNode(time_log_lebel)) eleParent.appendChild(endLogNode) durationLogNode = doc.createElement('TotalDuration') duration = end_time - self.start_time durationLogNode.appendChild( doc.createTextNode("%u" % (duration.total_seconds()))) eleParent.appendChild(durationLogNode) eleDoc.appendChild(eleParent) doc.appendChild(eleDoc) for key_ in self.command_order: if (key_ == prj or key_command == '#all'): if (key_command == '#all'): prj = key_ if (key_ != '__root'): eleProject = doc.createElement(prj) msgNode = None for key in self.projects[key_]: if (key == 'logs'): for msg in self.projects[prj]['logs']['message']: if ('text' in msg.keys()): nodeName = 'Message' if (msg['type'] == 'status'): nodeName = 'Status' eleMessage = doc.createElement(nodeName) eleText = doc.createTextNode(msg['text']) eleMessage.appendChild(eleText) msgNode = eleMessage elif ('error' in msg.keys()): eleError = doc.createElement('Error') eleErrorType = doc.createElement('type') eleErrorType.appendChild( doc.createTextNode(msg['error']['type'])) eleErrorText = doc.createElement('text') eleErrorText.appendChild( doc.createTextNode(msg['error']['text'])) eleError.appendChild(eleErrorType) eleError.appendChild(eleErrorText) #if warning/error begins without a parent 'Message' node, create an empty 'Message' parent node. if (msgNode == None): msgNode = doc.createElement('Message') eleMessage = msgNode msgNode.appendChild(eleError) if (key_ == '__root'): eleParent.appendChild(eleMessage) else: eleProject.appendChild(eleMessage) if ('DurationLabel' in self.projects[prj].keys()): durationLogNode = doc.createElement('Duration') durationLogNode.appendChild( doc.createTextNode( self.projects[prj]['DurationLabel'])) if (key_ == '__root'): eleParent.appendChild(durationLogNode) else: eleProject.appendChild(durationLogNode) if (key_ != '__root'): eleParent.appendChild(eleProject) eleDoc.appendChild(eleParent) try: #log reports can be saved uniquely named with date and time for easy review. ousr_date = datetime.now() prefix = self.logNamePrefix if (prefix == ''): prefix = 'log' recordUpdated = prefix + "_%04d%02d%02dT%02d%02d%02d.xml" % (ousr_date.year, ousr_date.month, ousr_date.day, \ ousr_date.hour, ousr_date.minute, ousr_date.second) if (self.logFileName.strip() != ''): recordUpdated = self.logFileName if (recordUpdated[-4:].lower() != '.xml'): recordUpdated += '.xml' #try to create the log-folder if not found! if (os.path.exists(self.logFolder) == False): os.mkdir(self.logFolder) logPath = os.path.join(self.logFolder, recordUpdated) c = open(logPath, "w") c.write(doc.toprettyxml()) c.close() except: print("\nError creating log file.")
def make_v0(apps, apks, repodir, repodict, requestsdict, fdroid_signing_key_fingerprints): """ aka index.jar aka index.xml """ doc = Document() def addElement(name, value, doc, parent): el = doc.createElement(name) el.appendChild(doc.createTextNode(value)) parent.appendChild(el) def addElementNonEmpty(name, value, doc, parent): if not value: return addElement(name, value, doc, parent) def addElementIfInApk(name, apk, key, doc, parent): if key not in apk: return value = str(apk[key]) addElement(name, value, doc, parent) def addElementCheckLocalized(name, app, key, doc, parent, default=''): """Fill in field from metadata or localized block For name/summary/description, they can come only from the app source, or from a dir in fdroiddata. They can be entirely missing from the metadata file if there is localized versions. This will fetch those from the localized version if its not available in the metadata file. Attributes should be alpha-sorted, so they must be added in alpha- sort order. """ el = doc.createElement(name) value = app.get(key) lkey = key[:1].lower() + key[1:] localized = app.get('localized') if not value and localized: for lang in ['en-US'] + [x for x in localized.keys()]: if not lang.startswith('en'): continue if lang in localized: value = localized[lang].get(lkey) if value: break if not value and localized and len(localized) > 1: lang = list(localized.keys())[0] value = localized[lang].get(lkey) if not value: value = default el.appendChild(doc.createTextNode(value)) parent.appendChild(el) root = doc.createElement("fdroid") doc.appendChild(root) repoel = doc.createElement("repo") repoel.setAttribute("icon", os.path.basename(repodict['icon'])) if 'maxage' in repodict: repoel.setAttribute("maxage", str(repodict['maxage'])) repoel.setAttribute("name", repodict['name']) pubkey, repo_pubkey_fingerprint = extract_pubkey() repoel.setAttribute("pubkey", pubkey.decode('utf-8')) repoel.setAttribute("timestamp", '%d' % repodict['timestamp'].timestamp()) repoel.setAttribute("url", repodict['address']) repoel.setAttribute("version", str(repodict['version'])) addElement('description', repodict['description'], doc, repoel) for mirror in repodict.get('mirrors', []): addElement('mirror', mirror, doc, repoel) root.appendChild(repoel) for command in ('install', 'uninstall'): for packageName in requestsdict[command]: element = doc.createElement(command) root.appendChild(element) element.setAttribute('packageName', packageName) for appid, appdict in apps.items(): app = metadata.App(appdict) if app.Disabled is not None: continue # Get a list of the apks for this app... apklist = [] apksbyversion = collections.defaultdict(lambda: []) for apk in apks: if apk.get('versionCode') and apk.get('packageName') == appid: apksbyversion[apk['versionCode']].append(apk) for versionCode, apksforver in apksbyversion.items(): fdroidsig = fdroid_signing_key_fingerprints.get(appid, {}).get('signer') fdroid_signed_apk = None name_match_apk = None for x in apksforver: if fdroidsig and x.get('signer', None) == fdroidsig: fdroid_signed_apk = x if common.apk_release_filename.match(x.get('apkName', '')): name_match_apk = x # choose which of the available versions is most # suiteable for index v0 if fdroid_signed_apk: apklist.append(fdroid_signed_apk) elif name_match_apk: apklist.append(name_match_apk) else: apklist.append(apksforver[0]) if len(apklist) == 0: continue apel = doc.createElement("application") apel.setAttribute("id", app.id) root.appendChild(apel) addElement('id', app.id, doc, apel) if app.added: addElement('added', app.added.strftime('%Y-%m-%d'), doc, apel) if app.lastUpdated: addElement('lastupdated', app.lastUpdated.strftime('%Y-%m-%d'), doc, apel) addElementCheckLocalized('name', app, 'Name', doc, apel) addElementCheckLocalized('summary', app, 'Summary', doc, apel) if app.icon: addElement('icon', app.icon, doc, apel) addElementCheckLocalized('desc', app, 'Description', doc, apel, '<p>No description available</p>') addElement('license', app.License, doc, apel) if app.Categories: addElement('categories', ','.join(app.Categories), doc, apel) # We put the first (primary) category in LAST, which will have # the desired effect of making clients that only understand one # category see that one. addElement('category', app.Categories[0], doc, apel) addElement('web', app.WebSite, doc, apel) addElement('source', app.SourceCode, doc, apel) addElement('tracker', app.IssueTracker, doc, apel) addElementNonEmpty('changelog', app.Changelog, doc, apel) addElementNonEmpty('author', app.AuthorName, doc, apel) addElementNonEmpty('email', app.AuthorEmail, doc, apel) addElementNonEmpty('donate', app.Donate, doc, apel) addElementNonEmpty('bitcoin', app.Bitcoin, doc, apel) addElementNonEmpty('litecoin', app.Litecoin, doc, apel) addElementNonEmpty('flattr', app.FlattrID, doc, apel) addElementNonEmpty('liberapay', app.LiberapayID, doc, apel) addElementNonEmpty('openCollective', app.OpenCollective, doc, apel) # These elements actually refer to the current version (i.e. which # one is recommended. They are historically mis-named, and need # changing, but stay like this for now to support existing clients. addElement('marketversion', app.CurrentVersion, doc, apel) addElement('marketvercode', app.CurrentVersionCode, doc, apel) if app.Provides: pv = app.Provides.split(',') addElementNonEmpty('provides', ','.join(pv), doc, apel) if app.RequiresRoot: addElement('requirements', 'root', doc, apel) # Sort the apk list into version order, just so the web site # doesn't have to do any work by default... apklist = sorted(apklist, key=lambda apk: apk['versionCode'], reverse=True) if 'antiFeatures' in apklist[0]: app.AntiFeatures.extend(apklist[0]['antiFeatures']) if app.AntiFeatures: addElementNonEmpty('antifeatures', ','.join(app.AntiFeatures), doc, apel) # Check for duplicates - they will make the client unhappy... for i in range(len(apklist) - 1): first = apklist[i] second = apklist[i + 1] if first['versionCode'] == second['versionCode'] \ and first['sig'] == second['sig']: if first['hash'] == second['hash']: raise FDroidException( '"{0}/{1}" and "{0}/{2}" are exact duplicates!'.format( repodir, first['apkName'], second['apkName'])) else: raise FDroidException( 'duplicates: "{0}/{1}" - "{0}/{2}"'.format( repodir, first['apkName'], second['apkName'])) current_version_code = 0 current_version_file = None for apk in apklist: file_extension = common.get_file_extension(apk['apkName']) # find the APK for the "Current Version" if current_version_code < apk['versionCode']: current_version_code = apk['versionCode'] if current_version_code < int(app.CurrentVersionCode): current_version_file = apk['apkName'] apkel = doc.createElement("package") apel.appendChild(apkel) versionName = apk.get('versionName') if not versionName: versionCodeStr = str(apk['versionCode'] ) # TODO build.versionCode should be int! for build in app.builds: if build[ 'versionCode'] == versionCodeStr and 'versionName' in build: versionName = build['versionName'] break if versionName: addElement('version', versionName, doc, apkel) addElement('versioncode', str(apk['versionCode']), doc, apkel) addElement('apkname', apk['apkName'], doc, apkel) addElementIfInApk('srcname', apk, 'srcname', doc, apkel) hashel = doc.createElement("hash") hashel.setAttribute('type', 'sha256') hashel.appendChild(doc.createTextNode(apk['hash'])) apkel.appendChild(hashel) addElement('size', str(apk['size']), doc, apkel) addElementIfInApk('sdkver', apk, 'minSdkVersion', doc, apkel) addElementIfInApk('targetSdkVersion', apk, 'targetSdkVersion', doc, apkel) addElementIfInApk('maxsdkver', apk, 'maxSdkVersion', doc, apkel) addElementIfInApk('obbMainFile', apk, 'obbMainFile', doc, apkel) addElementIfInApk('obbMainFileSha256', apk, 'obbMainFileSha256', doc, apkel) addElementIfInApk('obbPatchFile', apk, 'obbPatchFile', doc, apkel) addElementIfInApk('obbPatchFileSha256', apk, 'obbPatchFileSha256', doc, apkel) if 'added' in apk: addElement('added', apk['added'].strftime('%Y-%m-%d'), doc, apkel) if file_extension == 'apk': # sig is required for APKs, but only APKs addElement('sig', apk['sig'], doc, apkel) old_permissions = set() sorted_permissions = sorted(apk['uses-permission']) for perm in sorted_permissions: perm_name = perm[0] if perm_name.startswith("android.permission."): perm_name = perm_name[19:] old_permissions.add(perm_name) addElementNonEmpty('permissions', ','.join(sorted(old_permissions)), doc, apkel) for permission in sorted_permissions: permel = doc.createElement('uses-permission') if permission[1] is not None: permel.setAttribute('maxSdkVersion', '%d' % permission[1]) apkel.appendChild(permel) permel.setAttribute('name', permission[0]) for permission_sdk_23 in sorted(apk['uses-permission-sdk-23']): permel = doc.createElement('uses-permission-sdk-23') if permission_sdk_23[1] is not None: permel.setAttribute('maxSdkVersion', '%d' % permission_sdk_23[1]) apkel.appendChild(permel) permel.setAttribute('name', permission_sdk_23[0]) if 'nativecode' in apk: addElement('nativecode', ','.join(sorted(apk['nativecode'])), doc, apkel) addElementNonEmpty('features', ','.join(sorted(apk['features'])), doc, apkel) if current_version_file is not None \ and common.config['make_current_version_link'] \ and repodir == 'repo': # only create these namefield = common.config['current_version_name_source'] sanitized_name = re.sub(b'''[ '"&%?+=/]''', b'', app.get(namefield).encode('utf-8')) apklinkname = sanitized_name + os.path.splitext( current_version_file)[1].encode('utf-8') current_version_path = os.path.join(repodir, current_version_file).encode( 'utf-8', 'surrogateescape') if os.path.islink(apklinkname): os.remove(apklinkname) os.symlink(current_version_path, apklinkname) # also symlink gpg signature, if it exists for extension in (b'.asc', b'.sig'): sigfile_path = current_version_path + extension if os.path.exists(sigfile_path): siglinkname = apklinkname + extension if os.path.islink(siglinkname): os.remove(siglinkname) os.symlink(sigfile_path, siglinkname) if common.options.pretty: output = doc.toprettyxml(encoding='utf-8') else: output = doc.toxml(encoding='utf-8') with open(os.path.join(repodir, 'index.xml'), 'wb') as f: f.write(output) if 'repo_keyalias' in common.config \ or (common.options.nosign and 'repo_pubkey' in common.config): if common.options.nosign: logging.info( _("Creating unsigned index in preparation for signing")) else: logging.info(_("Creating signed index with this key (SHA256):")) logging.info("%s" % repo_pubkey_fingerprint) # Create a jar of the index... jar_output = 'index_unsigned.jar' if common.options.nosign else 'index.jar' p = FDroidPopen(['jar', 'cf', jar_output, 'index.xml'], cwd=repodir) if p.returncode != 0: raise FDroidException("Failed to create {0}".format(jar_output)) # Sign the index... signed = os.path.join(repodir, 'index.jar') if common.options.nosign: # Remove old signed index if not signing if os.path.exists(signed): os.remove(signed) else: signindex.config = common.config signindex.sign_jar(signed) # Copy the repo icon into the repo directory... icon_dir = os.path.join(repodir, 'icons') repo_icon = common.config.get('repo_icon', common.default_config['repo_icon']) iconfilename = os.path.join(icon_dir, os.path.basename(repo_icon)) if os.path.exists(repo_icon): shutil.copyfile(common.config['repo_icon'], iconfilename) else: logging.warning( _('repo_icon %s does not exist, generating placeholder.') % repo_icon) os.makedirs(os.path.dirname(iconfilename), exist_ok=True) try: import qrcode qrcode.make(common.config['repo_url']).save(iconfilename) except Exception: exampleicon = os.path.join(common.get_examples_dir(), common.default_config['repo_icon']) shutil.copy(exampleicon, iconfilename)
def writexml(filename, saveimg, bboxes, xmlpath): doc = Document() annotation = doc.createElement('annotation') doc.appendChild(annotation) folder = doc.createElement('folder') folder_name = doc.createTextNode('widerface') folder.appendChild(folder_name) annotation.appendChild(folder) filenamenode = doc.createElement('filename') filename_name = doc.createTextNode(filename) filenamenode.appendChild(filename_name) annotation.appendChild(filenamenode) source = doc.createElement('source') annotation.appendChild(source) database = doc.createElement('database') database.appendChild(doc.createTextNode('wider face Database')) source.appendChild(database) annotation_s = doc.createElement('annotation') annotation_s.appendChild(doc.createTextNode('PASCAL VOC2007')) source.appendChild(annotation_s) image = doc.createElement('image') image.appendChild(doc.createTextNode('flickr')) source.appendChild(image) flickrid = doc.createElement('flickrid') flickrid.appendChild(doc.createTextNode('-1')) source.appendChild(flickrid) owner = doc.createElement('owner') annotation.appendChild(owner) flickrid_o = doc.createElement('flickrid') flickrid_o.appendChild(doc.createTextNode('yanyu')) owner.appendChild(flickrid_o) name_o = doc.createElement('name') name_o.appendChild(doc.createTextNode('yanyu')) owner.appendChild(name_o) size = doc.createElement('size') annotation.appendChild(size) width = doc.createElement('width') width.appendChild(doc.createTextNode(str(saveimg.shape[1]))) height = doc.createElement('height') height.appendChild(doc.createTextNode(str(saveimg.shape[0]))) depth = doc.createElement('depth') depth.appendChild(doc.createTextNode(str(saveimg.shape[2]))) size.appendChild(width) size.appendChild(height) size.appendChild(depth) segmented = doc.createElement('segmented') segmented.appendChild(doc.createTextNode('0')) annotation.appendChild(segmented) for i in range(len(bboxes)): bbox = bboxes[i] objects = doc.createElement('object') annotation.appendChild(objects) object_name = doc.createElement('name') object_name.appendChild(doc.createTextNode('face')) objects.appendChild(object_name) pose = doc.createElement('pose') pose.appendChild(doc.createTextNode('Unspecified')) objects.appendChild(pose) truncated = doc.createElement('truncated') truncated.appendChild(doc.createTextNode('1')) objects.appendChild(truncated) difficult = doc.createElement('difficult') difficult.appendChild(doc.createTextNode('0')) objects.appendChild(difficult) bndbox = doc.createElement('bndbox') objects.appendChild(bndbox) xmin = doc.createElement('xmin') xmin.appendChild(doc.createTextNode(str(bbox[0]))) bndbox.appendChild(xmin) ymin = doc.createElement('ymin') ymin.appendChild(doc.createTextNode(str(bbox[1]))) bndbox.appendChild(ymin) xmax = doc.createElement('xmax') xmax.appendChild(doc.createTextNode(str(bbox[0] + bbox[2]))) bndbox.appendChild(xmax) ymax = doc.createElement('ymax') ymax.appendChild(doc.createTextNode(str(bbox[1] + bbox[3]))) bndbox.appendChild(ymax) f = open(xmlpath, "w") f.write(doc.toprettyxml(indent='')) f.close()
text = doc.createTextNode("Annie Hall") title.appendChild(text) director = doc.createElement("director") afilm.appendChild(director) text = doc.createTextNode("Woody Allen") director.appendChild(text) year = doc.createElement("year") afilm.appendChild(year) text = doc.createTextNode("1977") year.appendChild(text) afilm = doc.createElement("film") films.appendChild(afilm) title = doc.createElement("title") afilm.appendChild(title) text = doc.createTextNode("The Godfather") title.appendChild(text) director = doc.createElement("director") afilm.appendChild(director) text = doc.createTextNode("Francis Ford Coppola") director.appendChild(text) year = doc.createElement("year") afilm.appendChild(year) text = doc.createTextNode("1972s") year.appendChild(text) filename = "films.xml" f = open(filename, "w") f.write(doc.toprettyxml(indent=" ")) f.close()
# -*- coding: utf-8 -*- import xlrd from xml.dom.minidom import Document from xml.etree.ElementTree import Comment, Element import json infos = [] info_file = xlrd.open_workbook('numbers.xls') info_table = info_file.sheets()[0] row_count = info_table.nrows doc = Document() root = doc.createElement('root') doc.appendChild(root) numbers = doc.createElement('numbers') for row in range(row_count): number = doc.createElement('number') col1 = doc.createElement('column') col1.appendChild(doc.createTextNode('%d' % info_table.cell(row, 0).value)) number.appendChild(col1) col2 = doc.createElement('column') col2.appendChild(doc.createTextNode('%d' % info_table.cell(row, 1).value)) number.appendChild(col2) col3 = doc.createElement('column') col3.appendChild(doc.createTextNode('%d' % info_table.cell(row, 2).value)) number.appendChild(col3) numbers.appendChild(number) root.appendChild(numbers) file = open('numbers.xml', 'w') file.write(doc.toprettyxml(indent='')) file.close()
def create_fake_conf_file(self): doc = Document() config = doc.createElement('config') doc.appendChild(config) storage = doc.createElement('Storage') config.appendChild(storage) product = doc.createElement('Product') product_text = doc.createTextNode('HVS') product.appendChild(product_text) storage.appendChild(product) protocol = doc.createElement('Protocol') protocol_text = doc.createTextNode('iSCSI') protocol.appendChild(protocol_text) storage.appendChild(protocol) username = doc.createElement('UserName') username_text = doc.createTextNode('admin') username.appendChild(username_text) storage.appendChild(username) userpassword = doc.createElement('UserPassword') userpassword_text = doc.createTextNode('Admin@storage') userpassword.appendChild(userpassword_text) storage.appendChild(userpassword) url = doc.createElement('HVSURL') url_text = doc.createTextNode('http://100.115.10.69:8082/' 'deviceManager/rest/') url.appendChild(url_text) storage.appendChild(url) lun = doc.createElement('LUN') config.appendChild(lun) storagepool = doc.createElement('StoragePool') pool_text = doc.createTextNode('OpenStack_Pool') storagepool.appendChild(pool_text) lun.appendChild(storagepool) luntype = doc.createElement('LUNType') luntype_text = doc.createTextNode('Thick') luntype.appendChild(luntype_text) lun.appendChild(luntype) writetype = doc.createElement('WriteType') writetype_text = doc.createTextNode('1') writetype.appendChild(writetype_text) lun.appendChild(writetype) prefetchType = doc.createElement('Prefetch') prefetchType.setAttribute('Type', '2') prefetchType.setAttribute('Value', '20') lun.appendChild(prefetchType) iscsi = doc.createElement('iSCSI') config.appendChild(iscsi) defaulttargetip = doc.createElement('DefaultTargetIP') defaulttargetip_text = doc.createTextNode('100.115.10.68') defaulttargetip.appendChild(defaulttargetip_text) iscsi.appendChild(defaulttargetip) initiator = doc.createElement('Initiator') initiator.setAttribute('Name', 'iqn.1993-08.debian:01:ec2bff7ac3a3') initiator.setAttribute('TargetIP', '100.115.10.68') iscsi.appendChild(initiator) newefile = open(self.fake_conf_file, 'w') newefile.write(doc.toprettyxml(indent='')) newefile.close()
def ajax_validate(self, format="xml"): """ Validate data given the context, request and formview. The latter is needed to be able to use the correct widgets for processing the incoming data. """ model = self.form.model form = self.form self._process_data(form, form.view, self.request.params) effected = [] efferent = model.collectEfferentFields() ctls = [form.view.getRenderable(key) for key in \ self.request.params.keys()] ctls = [c for c in ctls if c] for ctl in ctls: for effected_field in efferent.get(ctl.bind, []): if not effected_field in effected: effected.append(effected_field) data = form.data state = {} for field in effected: ctrl = form.view.getRenderableByBind(field) if ctrl: state[ctrl.id] = {} state[ctrl.id]['readonly'] = model.isReadonly(field, data) state[ctrl.id]['relevant'] = model.isRelevant(field, data) state[ctrl.id]['required'] = model.isRequired(field, data) errors = [] error = None # Do actual validation try: fields = [control.bind for control in ctls] form.validate(fields=fields) except FormValidationError: error = sys.exc_info()[1] for control in ctls: if error and control.bind in error.errors: errors.append((control.id, control.alert or "Invalid value")) else: errors.append((control.id, "")) # Create the minidom document doc = Document() root = doc.createElement("validation") doc.appendChild(root) # Let's send back changes for f in state.keys(): for cmd in ['required', 'relevant', 'readonly']: command = doc.createElement("command") command.setAttribute("selector", "#%s" % f) command.setAttribute("name", cmd) command.setAttribute("value", "%s" % state[f][cmd]) root.appendChild(command) for field, message in errors: command = doc.createElement("command") command.setAttribute("selector", "#%s" % field) command.setAttribute("name", "alert") command.setAttribute("value", "%s" % message) root.appendChild(command) # Print our newly created XML return doc.toprettyxml(indent=" ")
def generate_xml(name, split_lines, img_size, class_ind): doc = Document() # 创建DOM文档对象 annotation = doc.createElement('annotation') doc.appendChild(annotation) title = doc.createElement('folder') title_text = doc.createTextNode('KITTI') title.appendChild(title_text) annotation.appendChild(title) img_name = name + '.png' title = doc.createElement('filename') title_text = doc.createTextNode(img_name) title.appendChild(title_text) annotation.appendChild(title) source = doc.createElement('source') annotation.appendChild(source) title = doc.createElement('database') title_text = doc.createTextNode('The KITTI Database') title.appendChild(title_text) source.appendChild(title) title = doc.createElement('annotation') title_text = doc.createTextNode('KITTI') title.appendChild(title_text) source.appendChild(title) size = doc.createElement('size') annotation.appendChild(size) title = doc.createElement('width') title_text = doc.createTextNode(str(img_size[1])) title.appendChild(title_text) size.appendChild(title) title = doc.createElement('height') title_text = doc.createTextNode(str(img_size[0])) title.appendChild(title_text) size.appendChild(title) title = doc.createElement('depth') title_text = doc.createTextNode(str(img_size[2])) title.appendChild(title_text) size.appendChild(title) for split_line in split_lines: line = split_line.strip().split() if line[0] in class_ind: object = doc.createElement('object') annotation.appendChild(object) title = doc.createElement('name') title_text = doc.createTextNode(line[0]) title.appendChild(title_text) object.appendChild(title) bndbox = doc.createElement('bndbox') object.appendChild(bndbox) title = doc.createElement('xmin') title_text = doc.createTextNode(str(int(float(line[4])))) title.appendChild(title_text) bndbox.appendChild(title) title = doc.createElement('ymin') title_text = doc.createTextNode(str(int(float(line[5])))) title.appendChild(title_text) bndbox.appendChild(title) title = doc.createElement('xmax') title_text = doc.createTextNode(str(int(float(line[6])))) title.appendChild(title_text) bndbox.appendChild(title) title = doc.createElement('ymax') title_text = doc.createTextNode(str(int(float(line[7])))) title.appendChild(title_text) bndbox.appendChild(title) # 将DOM对象doc写入文件 f = open('label_2car/xml/' + name + '.xml', 'w') f.write(doc.toprettyxml(indent='')) f.close()
def healthRecordViewCreate(xmlData): xmlData = addNodeToXML(xmlData, "healthRecord", "birthday", "1996-07-08") xmlData = delNodeFromXML(xmlData, "healthRecord", "personId") # default: 12 healthFileNum = str(int(time.time())) + str( datetime.datetime.now().microsecond) # default: random xmlData = addNodeToXML(xmlData, "healthRecord", "healthFileNumber", healthFileNum) machineNo = getAttributeFromXML(xmlData, "machineNo") name = getAttributeFromXML(xmlData, "name") idCard = getAttributeFromXML(xmlData, "idCard") try: nowLiveCode = getAttributeFromXML(xmlData, "nowLiveCode") except: print "Can not get nowLiveCode in nowLiveCode" xmlData = addNodeToXML(xmlData, "healthRecord", "nowLiveCode", "5") else: if len(nowLiveCode) == 0: xmlData = addNodeToXML(xmlData, "healthRecord", "nowLiveCode", "5") parser = XMLParser() item_name = {0: ["healthRecord"], 1: ["pastHistory"]} seriData = parser.get_seri(xmlData, item_name) print '**API: Create a new record.' dataSeri = TbhealthrecordSeri(data=seriData, many=True, context=seriData) if dataSeri.is_valid(): dataSeri.save() doc = Document() baseNode = doc.createElement("responseDatas") doc.appendChild(baseNode) rootNode = doc.createElement("healthRecord") baseNode.appendChild(rootNode) nodeName = doc.createElement("personId") rootNode.appendChild(nodeName) nodeVal = doc.createTextNode(healthFileNum) nodeName.appendChild(nodeVal) nodeName = doc.createElement("machineNo") rootNode.appendChild(nodeName) nodeVal = doc.createTextNode(machineNo) nodeName.appendChild(nodeVal) nodeName = doc.createElement("name") rootNode.appendChild(nodeName) nodeVal = doc.createTextNode(name) nodeName.appendChild(nodeVal) nodeName = doc.createElement("recordResultCode") rootNode.appendChild(nodeName) nodeVal = doc.createTextNode("0") nodeName.appendChild(nodeVal) nodeName = doc.createElement("recordResultDesc") rootNode.appendChild(nodeName) nodeVal = doc.createTextNode("身份证号码[" + idCard + "] 已经建档!") nodeName.appendChild(nodeVal) data = doc.toprettyxml(indent="", newl="", encoding="utf-8") print data return data else: print "**API ERROR(healthRecordViewCreate): Data is not valid." return ''
def generateXmlReport(self): """ Generates the XML reports to a given TestInfo object. """ try: doc = Document() testsuites= doc.createElement('testsuites') doc.appendChild(testsuites) parentElment = testsuites xml_content = None for cs in self.case_suite_list: if not cs.has_run: break testsuite = doc.createElement('testsuite') testsuites.appendChild(testsuite) testsuite.setAttribute('name',cs.path) testsuite.setAttribute('tests','1') testsuite.setAttribute('failures','0') xml_properties = doc.createElement('properties') testsuite.appendChild(xml_properties) property = doc.createElement('property') xml_properties.appendChild(property) systemout=doc.createElement('system-out') cdata = doc.createCDATASection("") systemout.appendChild(cdata) testsuite.appendChild(systemout) systemerr= doc.createElement('system-err') cdata=doc.createCDATASection("") systemerr.appendChild(cdata) testsuite.appendChild(systemerr) """ Appends a testcase section to the XML document. """ testCaseDurs = 0.0 failures = 0 for c in cs.case_list: if not c.has_run: break testcase = doc.createElement('testcase') testcase.setAttribute('classname','STF') testcase.setAttribute('name',c.id) testcase.setAttribute('time',six.text_type(c.elapsed_time)) failure = c.exitcode if failure == 1: error= doc.createElement('error') testcase.appendChild(error) error.setAttribute('type','error') error.setAttribute('message',c.fatal_error) cdata = doc.createCDATASection(str(c.__dict__)) error.appendChild(cdata) failures = failures + 1 testsuite.appendChild(testcase) testsuite.setAttribute('errors', six.text_type(failures)) testsuite.setAttribute('time', cs.elapsed_time) xml_content = doc.toprettyxml(indent='\t',encoding='UTF8') if xml_content is None: return if not os.path.exists('./testcase_reports'): os.mkdir('./testcase_reports') date = datetime.datetime.now().strftime("%Y%m%d-"+ time.tzname[1] + "-%H%M%S.%f") filename = os.path.join('./testcase_reports','TEST-STF-%s.xml' % date) with open(filename, 'wb') as report_file: report_file.write(xml_content) finally: pass
document = dom.createElement("Document") root.appendChild(document) document.appendChild( text_element('name', 'ROS Users of the World') ) document.appendChild( text_element('description', 'ROS Users of the World', True) ) files = [arg for arg in sys.argv[1:] if 'yaml' in arg] kml = [arg for arg in sys.argv[1:] if 'kml' in arg] if len(files)==0: for region in REGIONS: key = region.capitalize() url = PATTERN % region stream = urllib2.urlopen(url) document.appendChild( create_folder('ROS Users (%s)'%key, load(stream)) ) else: for fn in files: document.appendChild( create_folder(fn, load(open(fn)))) for style, color in STYLES.iteritems(): document.appendChild( create_style(style, color) ) if len(kml)>0: f = open(kml[0], 'w') f.write(dom.toprettyxml()) f.close() else: print "Content-type: text/xml" print print dom.toprettyxml()
def healexaminationViewSet(xmlData): # healthFileNumber = getAttributeFromXML(xmlData, "healthFileNumber") xmlData = delNodeFromXML(xmlData, "healthExamination", "personId") # default: 12 healthFileNum = getAttributeFromXML(xmlData, "healthFileNumber") machineNo = getAttributeFromXML(xmlData, "machineNo") name = getAttributeFromXML(xmlData, "name") parser = XMLParser() item_name = {0: ["healthExamination"]} seriData = parser.get_seri(xmlData, item_name) print '**API: Create a new record.' dataSeri = TbhealexaminationSeri(data=seriData, many=True, context=seriData) print dataSeri if dataSeri.is_valid(): dataSeri.save() doc = Document() baseNode = doc.createElement("responseDatas") doc.appendChild(baseNode) rootNode = doc.createElement("healthExamination") baseNode.appendChild(rootNode) nodeName = doc.createElement("businesskey") rootNode.appendChild(nodeName) nodeVal = doc.createTextNode(machineNo) nodeName.appendChild(nodeVal) nodeName = doc.createElement("personId") rootNode.appendChild(nodeName) nodeVal = doc.createTextNode(healthFileNum) nodeName.appendChild(nodeVal) nodeName = doc.createElement("machineNo") rootNode.appendChild(nodeName) nodeVal = doc.createTextNode(machineNo) nodeName.appendChild(nodeVal) nodeName = doc.createElement("name") rootNode.appendChild(nodeName) nodeVal = doc.createTextNode(name) nodeName.appendChild(nodeVal) nodeName = doc.createElement("recordResultCode") rootNode.appendChild(nodeName) nodeVal = doc.createTextNode("0") nodeName.appendChild(nodeVal) nodeName = doc.createElement("recordResultDesc") rootNode.appendChild(nodeName) nodeVal = doc.createTextNode("操作成功") nodeName.appendChild(nodeVal) data = doc.toprettyxml(indent="", newl="", encoding="utf-8") print data return data else: print "**API ERROR(healexaminationViewSet): Data is not valid." return ''
def RectWrite(NewRectList, NewRectNameList, NewScoreList, BasicInformation, outputXmlPath): #创建xml文件头 doc = Document() annotation = doc.createElement("annotation") doc.appendChild(annotation) folder = doc.createElement("folder") annotation.appendChild(folder) filename = doc.createElement("filename") annotation.appendChild(filename) path = doc.createElement("path") annotation.appendChild(path) source = doc.createElement("source") annotation.appendChild(source) database = doc.createElement("database") source.appendChild(database) size = doc.createElement("size") annotation.appendChild(size) width = doc.createElement("width") size.appendChild(width) height = doc.createElement("height") size.appendChild(height) depth = doc.createElement("depth") size.appendChild(depth) segmented = doc.createElement("segmented") annotation.appendChild(segmented) folder.appendChild(doc.createTextNode(BasicInformation[0])) filename.appendChild(doc.createTextNode(BasicInformation[1])) path.appendChild(doc.createTextNode(BasicInformation[2])) database.appendChild(doc.createTextNode("Unknown")) width.appendChild(doc.createTextNode(BasicInformation[3])) height.appendChild(doc.createTextNode(BasicInformation[4])) depth.appendChild(doc.createTextNode(BasicInformation[5])) segmented.appendChild(doc.createTextNode("0")) for NR_index, NewRect in enumerate(NewRectList): object = doc.createElement("object") annotation.appendChild(object) name = doc.createElement("name") object.appendChild(name) pose = doc.createElement("pose") object.appendChild(pose) truncated = doc.createElement("truncated") object.appendChild(truncated) difficult = doc.createElement("difficult") object.appendChild(difficult) bndbox = doc.createElement("bndbox") object.appendChild(bndbox) xmin = doc.createElement("xmin") bndbox.appendChild(xmin) ymin = doc.createElement("ymin") bndbox.appendChild(ymin) xmax = doc.createElement("xmax") bndbox.appendChild(xmax) ymax = doc.createElement("ymax") bndbox.appendChild(ymax) score = doc.createElement("score") object.appendChild(score) name.appendChild(doc.createTextNode(NewRectNameList[NR_index])) pose.appendChild(doc.createTextNode("Unspecified")) truncated.appendChild(doc.createTextNode("0")) difficult.appendChild(doc.createTextNode("0")) xmin.appendChild(doc.createTextNode(str(NewRect[0]))) ymin.appendChild(doc.createTextNode(str(NewRect[1]))) xmax.appendChild(doc.createTextNode(str(NewRect[2]))) ymax.appendChild(doc.createTextNode(str(NewRect[3]))) score.appendChild(doc.createTextNode(NewScoreList[NR_index])) #xml文件保存 XMLfile = open(outputXmlPath, "w") XMLfile.write(doc.toprettyxml(indent=" ")) XMLfile.close()
def parse_page(): url = 'https://movie.douban.com/coming' try: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36'} r = requests.get(url, headers=headers) #print(r) if r.status_code == 200: return r.text return None except RequestException: return None res = r.text soup = BeautifulSoup(res, 'html.parser') trs = soup.find('table', 'coming_list').find('tbody').find_all('tr') coming = '' # print(div) nowplaying = '' for i in range(0, 4): print(i) if trs[i].find_all('td')[0].text.strip() != None: time = trs[i].find_all('td')[0].text.strip() else: time = '暂无上映日期' if trs[i].find_all('td')[1].text.strip() != None: name = trs[i].find_all('td')[1].text.strip() else: name = '暂无片名' if trs[i].find_all('td')[2].text.strip() != None: type = trs[i].find_all('td')[2].text.strip() else: type = '暂无类型' if trs[i].find_all('td')[3].text.strip() != None: country = trs[i].find_all('td')[3].text.strip() else: country = '暂无地区' if trs[i].find_all('td')[4].text.strip() != None: wanting = trs[i].find_all('td')[4].text.strip() else: wanting = '暂无想看人数' if trs[i].find_all('td')[1].find('a').get('href').strip() != None: plot_simple = trs[i].find_all('td')[1].find('a').get('href').strip() else: plot_simple = '暂无简介' time_list.append(time) name_list.append(name) type_list.append(type) country_list.append(country) wanting_list.append(wanting) plot_simple_list.append(plot_simple) # print(name_list) # print(rating_list) # print(plot_simple_list) # if i < 10 : # print(div[i].find("li", attrs={"class": 'srating'}).find('span','subject-rate')) file = xlwt.Workbook() table = file.add_sheet('即将上映') table.write(0, 0, "id") table.write(0, 1, "上映时间") table.write(0, 2, "片名") table.write(0, 3, "类型") table.write(0, 4, "地区") table.write(0, 5, "想看人数") table.write(0, 6, "简介") # 写入xml文件中 doc = Document() # 创建根节点movielist movielist = doc.createElement('movielist') # 根节点插入dom树 doc.appendChild(movielist) # 对于每组数据创建父节点movie,子节点title,rating,plot_simple for i in range(len(name_list)): movie = doc.createElement('movie') movielist.appendChild(movie) # 片名 Title = doc.createElement('title') Title_text = doc.createTextNode(name_list[i]) Title.appendChild(Title_text) movie.appendChild(Title) # 上映时间 Time = doc.createElement('time') Time_text = doc.createTextNode(time_list[i]) Time.appendChild(Time_text) movie.appendChild(Time) # 类型 Type= doc.createElement('type') Type_text = doc.createTextNode(type_list[i]) Type.appendChild(Type_text) movie.appendChild(Type) # 地区 Country = doc.createElement('country') Country_text = doc.createTextNode(country_list[i]) Country.appendChild(Country_text) movie.appendChild(Country) # 想看人数 Wanting = doc.createElement('wanting') Wanting_text = doc.createTextNode(str(wanting_list[i])) Wanting.appendChild(Wanting_text) movie.appendChild(Wanting) # 简介 Plot_simple = doc.createElement('plot_simple') Plot_simple_text = doc.createTextNode(plot_simple_list[i]) Plot_simple.appendChild(Plot_simple_text) movie.appendChild(Plot_simple) with open('Later.xml', 'wb') as f: f.write(doc.toprettyxml(indent='\t', encoding='utf-8'))
class XmlManager(): # --------------------------------------------------------------------------- # Class variables # --------------------------------------------------------------------------- averageTag = "unweightedAverageAllMetrics" measureTag = "measure" measuresTag = "measures" categoryTag = "category" typeTag = "tag" sizeTag = "size" corefTag = "coreference_evaluation" # --------------------------------------------------------------------------- # Class methods # --------------------------------------------------------------------------- def __init__(self, outputFilePath): # first check if the outputFilePath exists # otherwise prompt the error and stop execution if not os.path.exists(outputFilePath): dir = os.path.dirname(outputFilePath) if not os.path.exists(dir): errorMessage = "ERROR: Incorrect output file path %s " % outputFilePath print errorMessage self.forcedExiting() self.doc = Document() # init the xml document self.corpus = self.doc.createElement(self.corefTag) self.doc.appendChild(self.corpus) # output file name self.outputFileName = outputFilePath def xmlConvertCumulative(self, resultsOverAllMetricsAndOverlap): for metric in resultsOverAllMetricsAndOverlap.keys(): metricElement = self.doc.createElement(metric) self.corpus.appendChild(metricElement) metricOverlap = resultsOverAllMetricsAndOverlap.get(metric) for overlap in metricOverlap.keys(): overlapElement = self.doc.createElement(overlap) metricElement.appendChild(overlapElement) semValues = metricOverlap.get(overlap) for semResults in semValues: self.xmlConvert(semResults[0], semResults[1], semResults[2], overlapElement) def xmlConvert(self, semanticCategory, sampleSize, results, parent=None): category = self.doc.createElement(self.categoryTag) category.setAttribute(self.typeTag, semanticCategory) category.setAttribute(self.sizeTag, str(sampleSize)) for key in results.keys(): if key == self.averageTag: self.appendUnweightedAverage(results.get(key), parent) continue measures = self.doc.createElement(self.measuresTag) measures.setAttribute(self.typeTag, key) category.appendChild(measures) analysisResults = results.get(key) for result in analysisResults.keys(): measure = self.doc.createElement(self.measureTag) measure.setAttribute(self.typeTag, result) resultText = self.doc.createTextNode( str(analysisResults.get(result))) measure.appendChild(resultText) measures.appendChild(measure) if parent == None: self.corpus.appendChild(category) else: parent.appendChild(category) def appendUnweightedAverage(self, value, parent=None): category = self.doc.createElement(self.categoryTag) category.setAttribute(self.typeTag, self.averageTag) resultText = self.doc.createTextNode(str(value)) category.appendChild(resultText) if parent == None: self.corpus.appendChild(category) else: parent.appendChild(category) def xmlRender(self): try: outputFile = open(self.outputFileName, "w") outputFile.write(self.doc.toprettyxml(indent=" ")) outputFile.close() except: print "ERROR: Could not locate output file. Rendering to std output." print self.doc.toprettyxml(indent=" ") def forcedExiting(self): print 'ERROR: Check the log file for more details.' sys.exit(-1)
def generate_annoXml_and_text_from_widerSplit(widerSplit_file, subDir, xml_save_folder): global samples_width global samples_height global samples with open(widerSplit_file, 'r') as split_file: while True: img_filename = split_file.readline()[:-1] if img_filename == "": break print("img_filename:%s" % {img_filename}) imgpath = root_dir + '/JPEGImages/' + subDir + '/images/' + img_filename #label text file path label_image_file = labelDir + '/' + img_filename.split( '.')[-2].split('/')[-1] label_file = open(label_image_file, 'w') #xml file path xml_file_path = xml_save_folder + '/' + img_filename.split( '.')[-2].split('/')[-1] + '.xml' print('xml_file_path: %s' % {xml_file_path}) source_img = cv2.imread(imgpath) doc = Document() annotation = doc.createElement('annotation') # annotation element doc.appendChild(annotation) folder = doc.createElement('folder') folder_name = doc.createTextNode('wider_face') folder.appendChild(folder_name) annotation.appendChild(folder) filename_node = doc.createElement('filename') filename_name = doc.createTextNode(img_filename) filename_node.appendChild(filename_name) annotation.appendChild(filename_node) source = doc.createElement('source') # source sub_element annotation.appendChild(source) database = doc.createElement('database') database.appendChild(doc.createTextNode('wider_face Database')) annotation.appendChild(database) annotation_s = doc.createElement('annotation') annotation_s.appendChild(doc.createTextNode('PASCAL VOC2007')) source.appendChild(annotation_s) image = doc.createElement('image') image.appendChild(doc.createTextNode('flickr')) source.appendChild(image) flickrid = doc.createElement('flickrid') flickrid.appendChild(doc.createTextNode('-1')) source.appendChild(flickrid) owner = doc.createElement('owner') # company element annotation.appendChild(owner) flickrid_o = doc.createElement('flickrid') flickrid_o.appendChild(doc.createTextNode('deep')) owner.appendChild(flickrid_o) name_o = doc.createElement('name') name_o.appendChild(doc.createTextNode('deep')) owner.appendChild(name_o) size = doc.createElement('size') # img size info element annotation.appendChild(size) width = doc.createElement('width') width.appendChild(doc.createTextNode(str(source_img.shape[1]))) height = doc.createElement('height') height.appendChild(doc.createTextNode(str(source_img.shape[0]))) depth = doc.createElement('depth') depth.appendChild(doc.createTextNode(str(source_img.shape[2]))) size.appendChild(width) size.appendChild(height) size.appendChild(depth) # split_file numbox numbbox = int(split_file.readline()) for _ in range(numbbox): line = split_file.readline() anno_bbox = line.split(' ') x_min = anno_bbox[0] y_min = anno_bbox[1] width = anno_bbox[2] height = anno_bbox[3] blur = anno_bbox[4] intBlur = int(blur) invalid = anno_bbox[7] occlusion = anno_bbox[8] intOcclu_ = int(occlusion) difficult = 0 newline = x_min + ' ' + y_min + ' ' + width + ' ' + height + ' \n' if int(invalid) == 1 or intBlur == 2 or intOcclu_ == 2: continue if int(width) < minDetectSize or int(height) < minDetectSize: continue samples += 1 if int(width) >= min_size and int(width) < max_size: samples_width += 1 if int(height) >= min_size and int(height) < max_size: samples_height += 1 # label text file label_file.writelines(newline) # xml annotation file objects = doc.createElement('object') annotation.appendChild(objects) object_name = doc.createElement('name') object_name.appendChild(doc.createTextNode('face')) objects.appendChild(object_name) blur_node = doc.createElement('blur') blur_node.appendChild(doc.createTextNode(blur)) objects.appendChild(blur_node) occlusion_node = doc.createElement('occlusion') occlusion_node.appendChild(doc.createTextNode(occlusion)) objects.appendChild(occlusion_node) difficult_node = doc.createElement('difficult') difficult_node.appendChild(doc.createTextNode(str(difficult))) objects.appendChild(difficult_node) boundbox = doc.createElement('bndbox') # boundbox objects.appendChild(boundbox) xmin = doc.createElement('xmin') xmin.appendChild(doc.createTextNode(x_min)) boundbox.appendChild(xmin) ymin = doc.createElement('ymin') ymin.appendChild(doc.createTextNode(y_min)) boundbox.appendChild(ymin) xmax = doc.createElement('xmax') xmax.appendChild( doc.createTextNode(str(int(x_min) + int(width)))) boundbox.appendChild(xmax) ymax = doc.createElement('ymax') ymax.appendChild( doc.createTextNode(str(int(y_min) + int(height)))) boundbox.appendChild(ymax) label_file.close() xml_file = open(xml_file_path, 'w') xml_file.write(doc.toprettyxml(indent='')) xml_file.close() data = open(label_image_file, "r").read() if len(data) == 0: os.remove(label_image_file) split_file.close()
def bdExportCtrl(): selection = pm.ls(sl=1, type='transform') xmlPath = 'c:\\Users\\bogdan_d\\Documents\\bdPyScripts\\controllers\\' xmlFile = '' if selection: if len(selection) == 1: cvPos = {} toExport = selection[0] shape = toExport.getShapes() xmlFile = toExport.name().replace(toExport.namespace(), '') + '.xml' xmlDoc = Document() root = xmlDoc.createElement('controller') root.setAttribute( 'name', toExport.name().replace(toExport.namespace(), '')) xmlDoc.appendChild(root) for s in shape: if 'Orig' not in s.name(): if s.type() == 'nurbsCurve': node = xmlDoc.createElement('shape') periodic = '0' if s.form() == 'periodic': periodic = '1' node.setAttribute('periodic', periodic) degree = s.degree() node.setAttribute('degree', str(degree)) cvPos = [(x.x, x.y, x.z) for x in s.getCVs(space='world')] node.setAttribute('cvs', str(cvPos)) knots = [k for k in s.getKnots()] node.setAttribute('knots', str(knots)) node.setAttribute( 'name', s.name().replace(toExport.namespace(), '')) root.appendChild(node) else: pm.warning('You can only export NURBS curves') break attrListNode = xmlDoc.createElement('attributesList') udAttr = toExport.listAttr(ud=True) for attr in udAttr: attrNode = xmlDoc.createElement('attribute') attrName = attr.name(includeNode=0).replace( toExport.namespace(), '') attrType = attr.type() if attrType == 'enum': dictEnum = attr.getEnums() val = [str(k) for k in dictEnum.keys()] enumValues = str(val).strip('[]').replace('\'', '') attrNode.setAttribute('enumValues', enumValues) attrLocked = attr.get(l=True) attrCB = attr.get(cb=True) attrValue = attr.get() attrMinMax = str(attr.getRange()) attrNode.setAttribute('name', attrName) attrNode.setAttribute('type', attrType) attrNode.setAttribute('locked', str(attrLocked)) attrNode.setAttribute('channelBox', str(attrCB)) attrNode.setAttribute('value', str(attrValue)) attrNode.setAttribute('minMax', attrMinMax) attrListNode.appendChild(attrNode) root.appendChild(attrListNode) f = open(xmlPath + xmlFile, 'w') f.write(xmlDoc.toprettyxml()) f.close() else: pm.warning('Select only one controller !!!') else: pm.warning('Select a Nurbs Curve')
def writeXml(tmp, imgname, w, h, objbud, wxml): doc = Document() # owner annotation = doc.createElement('annotation') doc.appendChild(annotation) # owner folder = doc.createElement('folder') annotation.appendChild(folder) folder_txt = doc.createTextNode("VOC2005") folder.appendChild(folder_txt) filename = doc.createElement('filename') annotation.appendChild(filename) filename_txt = doc.createTextNode(imgname) filename.appendChild(filename_txt) # ones# source = doc.createElement('source') annotation.appendChild(source) database = doc.createElement('database') source.appendChild(database) database_txt = doc.createTextNode("The VOC2005 Database") database.appendChild(database_txt) annotation_new = doc.createElement('annotation') source.appendChild(annotation_new) annotation_new_txt = doc.createTextNode("PASCAL VOC2005") annotation_new.appendChild(annotation_new_txt) image = doc.createElement('image') source.appendChild(image) image_txt = doc.createTextNode("flickr") image.appendChild(image_txt) # onee# # twos# size = doc.createElement('size') annotation.appendChild(size) width = doc.createElement('width') size.appendChild(width) width_txt = doc.createTextNode(str(w)) width.appendChild(width_txt) height = doc.createElement('height') size.appendChild(height) height_txt = doc.createTextNode(str(h)) height.appendChild(height_txt) depth = doc.createElement('depth') size.appendChild(depth) depth_txt = doc.createTextNode("3") depth.appendChild(depth_txt) # twoe# segmented = doc.createElement('segmented') annotation.appendChild(segmented) segmented_txt = doc.createTextNode("0") segmented.appendChild(segmented_txt) for i in range(0, int(len(objbud))): objbuds = objbud[i].split(' ') #print(objbuds) # threes# object_new = doc.createElement("object") annotation.appendChild(object_new) name = doc.createElement('name') object_new.appendChild(name) name_txt = doc.createTextNode(objbuds[0]) name.appendChild(name_txt) pose = doc.createElement('pose') object_new.appendChild(pose) pose_txt = doc.createTextNode("Unspecified") pose.appendChild(pose_txt) truncated = doc.createElement('truncated') object_new.appendChild(truncated) truncated_txt = doc.createTextNode("0") truncated.appendChild(truncated_txt) difficult = doc.createElement('difficult') object_new.appendChild(difficult) difficult_txt = doc.createTextNode("0") difficult.appendChild(difficult_txt) # threes-1# bndbox = doc.createElement('bndbox') object_new.appendChild(bndbox) xmin = doc.createElement('xmin') bndbox.appendChild(xmin) xmin_txt = doc.createTextNode( str(int((float(objbuds[1]) * w - float(objbuds[3]) * w / 2.0)))) xmin.appendChild(xmin_txt) ymin = doc.createElement('ymin') bndbox.appendChild(ymin) ymin_txt = doc.createTextNode( str(int(float(objbuds[2]) * h - float(objbuds[4]) * h / 2.0))) ymin.appendChild(ymin_txt) xmax = doc.createElement('xmax') bndbox.appendChild(xmax) xmax_txt = doc.createTextNode( str(int(float(objbuds[1]) * w + float(objbuds[3]) * w / 2.0))) xmax.appendChild(xmax_txt) ymax = doc.createElement('ymax') bndbox.appendChild(ymax) ymax_txt = doc.createTextNode( str(int(float(objbuds[2]) * h + float(objbuds[4]) * h / 2))) ymax.appendChild(ymax_txt) # threee-1# # threee# tempfile = tmp + "test.xml" with open(tempfile, "w") as f: f.write(doc.toprettyxml(indent='\t')) rewrite = open(tempfile, "r") lines = rewrite.read().split('\n') newlines = lines[1:len(lines) - 1] fw = open(wxml, "w") for i in range(0, len(newlines)): fw.write(newlines[i] + '\n') fw.close() rewrite.close() os.remove(tempfile) return
class CustomXMLBuilder(object): """ This class builds the XML used to describe songs. """ log.info('CustomXMLBuilder Loaded') def __init__(self): """ Set up the custom builder. """ # Create the minidom document self.custom_xml = Document() self.new_document() self.add_lyrics_to_song() def new_document(self): """ Create a new custom XML document. """ # Create the <song> base element self.song = self.custom_xml.createElement('song') self.custom_xml.appendChild(self.song) self.song.setAttribute('version', '1.0') def add_lyrics_to_song(self): """ Set up and add a ``<lyrics>`` tag which contains the lyrics of the custom item. """ # Create the main <lyrics> element self.lyrics = self.custom_xml.createElement('lyrics') self.lyrics.setAttribute('language', 'en') self.song.appendChild(self.lyrics) def add_verse_to_lyrics(self, verse_type, number, content): """ Add a verse to the ``<lyrics>`` tag. :param verse_type: A string denoting the type of verse. Possible values are "Chorus", "Verse", "Bridge", and "Custom". :param number: An integer denoting the number of the item, for example: verse 1. :param content: The actual text of the verse to be stored. """ verse = self.custom_xml.createElement('verse') verse.setAttribute('type', verse_type) verse.setAttribute('label', number) self.lyrics.appendChild(verse) # add data as a CDATA section to protect the XML from special chars cds = self.custom_xml.createCDATASection(content) verse.appendChild(cds) def _dump_xml(self): """ Debugging aid to dump XML so that we can see what we have. """ return self.custom_xml.toprettyxml(indent=' ') def extract_xml(self): """ Extract our newly created XML custom. """ return self.custom_xml.toxml('utf-8')
safetyatt = doc.createElement("SafetyAttribute") nameatt = doc.createElement("Name") nameatt.setAttribute("name", i) safetyatt.appendChild(nameatt) aux = cweAtts.get(i) for j in range(0, len(aux)): tmp = "" tmp += aux[j] valueatt = doc.createElement("Value") valueatt.setAttribute("value", tmp) if (i == "Owner"): metricas = reglas(i, tmp) for k in range(0, len(metricas)): metrics = doc.createElement("Metric") metrics.setAttribute("metric", metricas[k][0]) metrics.setAttribute("value", metricas[k][1]) metrics.setAttribute("score", str(metricas[k][2])) valueatt.appendChild(metrics) safetyatt.appendChild(valueatt) rules.appendChild(safetyatt) file = open("rules.xml", "wb") try: file.write(doc.toprettyxml(indent=" ", encoding="UTF-8")) finally: file.close()
class OpenVASReportGenerator(ReportGenerator): """ This class generates a report with the method printToFile(fileName) which contains the information of all the vulnerabilities notified to this object through the method logVulnerability(vulnerabilityTypeName,level,url,parameter,info). The format of the file is XML and it has the following structure: <report type="security"> <generatedBy id="WAVES 1.0.0"/> <vulnerabilityTypeList> <vulnerabilityType name="SQL Injection"> <vulnerabilityTypeList> <vulnerabilityType name="SQL Injection"> <vulnerabilityList> <vulnerability level="3"> <url>http://www.a.com</url> <parameters>id=23</parameters> <info>SQL Injection</info> </vulnerability> </vulnerabilityList> </vulnerabilityType> </vulnerabilityTypeList> </report> """ def __init__(self): self.__xmlDoc = Document() self.__infos = {} self.__flawTypes = {} self.__vulns = {} self.__anomalies = {} self.__vulnCount = 0 self.__anomCount = 0 def setReportInfo(self, target, scope=None, date_string="", version=""): self.__infos["target"] = target self.__infos["date"] = date_string self.__infos["version"] = version if scope: self.__infos["scope"] = scope # Vulnerabilities def addVulnerabilityType(self, name, description="", solution="", references={}): if name not in self.__flawTypes: self.__flawTypes[name] = { 'desc': description, 'sol': solution, 'ref': references } if name not in self.__vulns: self.__vulns[name] = [] def logVulnerability(self, category=None, level=0, request=None, parameter="", info=""): """ Store the information about the vulnerability to be printed later. The method printToFile(fileName) can be used to save in a file the vulnerabilities notified through the current method. """ vuln_dict = { "method": request.method, "hostname": request.hostname, "port": request.port, "path": request.file_path, "info": info, "level": level, "parameter": parameter, "http_request": request.http_repr, "curl_command": request.curl_repr, } if category not in self.__vulns: self.__vulns[category] = [] self.__vulns[category].append(vuln_dict) self.__vulnCount += 1 # Anomalies def addAnomalyType(self, name, description="", solution="", references={}): if name not in self.__flawTypes: self.__flawTypes[name] = { 'desc': description, 'sol': solution, 'ref': references } if name not in self.__anomalies: self.__anomalies[name] = [] def logAnomaly(self, category=None, level=0, request=None, parameter="", info=""): """ Store the information about the vulnerability to be printed later. The method printToFile(fileName) can be used to save in a file the vulnerabilities notified through the current method. """ anom_dict = { "method": request.method, "hostname": request.hostname, "port": request.port, "path": request.file_path, "info": info, "level": level, "parameter": parameter, "http_request": request.http_repr, "curl_command": request.curl_repr, } if category not in self.__anomalies: self.__anomalies[category] = [] self.__anomalies[category].append(anom_dict) self.__anomCount += 1 def generateReport(self, filename): """ Create a xml file with a report of the vulnerabilities which have been logged with the method logVulnerability(vulnerabilityTypeName,level,url,parameter,info) """ uuid_report = str(uuid.uuid1()) report = self.__xmlDoc.createElement("report") report.setAttribute("extension", "xml") report.setAttribute("id", uuid_report) report.setAttribute("type", "scan") report.setAttribute("content_type", "text/html") report.setAttribute("format_id", "a994b278-1f62-11e1-96ac-406186ea4fc5") self.__xmlDoc.appendChild(report) # Add report infos report_infos = self.__xmlDoc.createElement("report") report_infos.setAttribute("id", uuid_report) scan_run_status = self.__xmlDoc.createElement("scan_run_status") scan_run_status.appendChild(self.__xmlDoc.createTextNode("Done")) report_infos.appendChild(scan_run_status) scan_start = self.__xmlDoc.createElement("scan_start") scan_start.appendChild( self.__xmlDoc.createTextNode(self.__infos["date"])) report_infos.appendChild(scan_start) results = self.__xmlDoc.createElement("results") results.setAttribute("start", "1") results.setAttribute("max", str(self.__vulnCount + self.__anomCount)) # Loop on each flaw classification for flawType in self.__flawTypes: classification = "" flaw_dict = {} if flawType in self.__vulns: classification = "vulnerability" flaw_dict = self.__vulns elif flawType in self.__anomalies: classification = "anomaly" flaw_dict = self.__anomalies for flaw in flaw_dict[flawType]: result = self.__xmlDoc.createElement("result") result.setAttribute("id", str(uuid.uuid4())) subnet = self.__xmlDoc.createElement("subnet") subnet.appendChild( self.__xmlDoc.createTextNode(flaw["hostname"])) result.appendChild(subnet) host = self.__xmlDoc.createElement("host") host.appendChild(self.__xmlDoc.createTextNode( flaw["hostname"])) result.appendChild(host) port = self.__xmlDoc.createElement("port") port.appendChild( self.__xmlDoc.createTextNode(str(flaw["port"]))) result.appendChild(port) nvt = self.__xmlDoc.createElement("nvt") nvt.setAttribute("oid", str(uuid.uuid4())) name = self.__xmlDoc.createElement("name") name.appendChild(self.__xmlDoc.createTextNode(flawType)) nvt.appendChild(name) family = self.__xmlDoc.createElement("family") family.appendChild( self.__xmlDoc.createTextNode(classification)) nvt.appendChild(family) cvss_base = self.__xmlDoc.createElement("cvss_base") cvss_base.appendChild(self.__xmlDoc.createTextNode("0.0")) nvt.appendChild(cvss_base) risk_factor = self.__xmlDoc.createElement("risk_factor") risk_factor.appendChild( self.__xmlDoc.createTextNode(str(flaw["level"]))) nvt.appendChild(risk_factor) cve = self.__xmlDoc.createElement("cve") cve.appendChild(self.__xmlDoc.createTextNode("")) nvt.appendChild(cve) bid = self.__xmlDoc.createElement("bid") bid.appendChild(self.__xmlDoc.createTextNode("")) nvt.appendChild(bid) tags = self.__xmlDoc.createElement("tags") tags.appendChild(self.__xmlDoc.createTextNode("")) nvt.appendChild(tags) certs = self.__xmlDoc.createElement("certs") certs.appendChild(self.__xmlDoc.createTextNode("")) nvt.appendChild(certs) xref = self.__xmlDoc.createElement("xref") xref.appendChild(self.__xmlDoc.createTextNode("NOXREF")) nvt.appendChild(xref) result.appendChild(nvt) threat = self.__xmlDoc.createElement("threat") threat.appendChild( self.__xmlDoc.createTextNode(str(flaw["level"]))) result.appendChild(threat) description = self.__xmlDoc.createElement("description") description.appendChild( self.__xmlDoc.createCDATASection(flaw["info"])) result.appendChild(description) original_threat = self.__xmlDoc.createElement( "original_threat") original_threat.appendChild( self.__xmlDoc.createTextNode(str(flaw["level"]))) result.appendChild(original_threat) results.appendChild(result) report_infos.appendChild(results) report.appendChild(report_infos) f = open(filename, "w") try: f.write(self.__xmlDoc.toprettyxml(indent=" ", encoding="UTF-8")) finally: f.close()
def save_to_xml(save_path, im_height, im_width, objects_axis, label_name): im_depth = 0 object_num = len(objects_axis) doc = Document() annotation = doc.createElement('annotation') doc.appendChild(annotation) folder = doc.createElement('folder') folder_name = doc.createTextNode('VOC2007') folder.appendChild(folder_name) annotation.appendChild(folder) filename = doc.createElement('filename') filename_name = doc.createTextNode('000024.jpg') filename.appendChild(filename_name) annotation.appendChild(filename) source = doc.createElement('source') annotation.appendChild(source) database = doc.createElement('database') database.appendChild(doc.createTextNode('The VOC2007 Database')) source.appendChild(database) annotation_s = doc.createElement('annotation') annotation_s.appendChild(doc.createTextNode('PASCAL VOC2007')) source.appendChild(annotation_s) image = doc.createElement('image') image.appendChild(doc.createTextNode('flickr')) source.appendChild(image) flickrid = doc.createElement('flickrid') flickrid.appendChild(doc.createTextNode('322409915')) source.appendChild(flickrid) owner = doc.createElement('owner') annotation.appendChild(owner) flickrid_o = doc.createElement('flickrid') flickrid_o.appendChild(doc.createTextNode('knautia')) owner.appendChild(flickrid_o) name_o = doc.createElement('name') name_o.appendChild(doc.createTextNode('yang')) owner.appendChild(name_o) size = doc.createElement('size') annotation.appendChild(size) width = doc.createElement('width') width.appendChild(doc.createTextNode(str(im_width))) height = doc.createElement('height') height.appendChild(doc.createTextNode(str(im_height))) depth = doc.createElement('depth') depth.appendChild(doc.createTextNode(str(im_depth))) size.appendChild(width) size.appendChild(height) size.appendChild(depth) segmented = doc.createElement('segmented') segmented.appendChild(doc.createTextNode('0')) annotation.appendChild(segmented) for i in range(object_num): objects = doc.createElement('object') annotation.appendChild(objects) object_name = doc.createElement('name') object_name.appendChild(doc.createTextNode(label_name[int(objects_axis[i][-1])])) objects.appendChild(object_name) pose = doc.createElement('pose') pose.appendChild(doc.createTextNode('Unspecified')) objects.appendChild(pose) truncated = doc.createElement('truncated') truncated.appendChild(doc.createTextNode('1')) objects.appendChild(truncated) difficult = doc.createElement('difficult') difficult.appendChild(doc.createTextNode('0')) objects.appendChild(difficult) bndbox = doc.createElement('bndbox') objects.appendChild(bndbox) x0 = doc.createElement('x0') x0.appendChild(doc.createTextNode(str((objects_axis[i][0])))) bndbox.appendChild(x0) y0 = doc.createElement('y0') y0.appendChild(doc.createTextNode(str((objects_axis[i][1])))) bndbox.appendChild(y0) x1 = doc.createElement('x1') x1.appendChild(doc.createTextNode(str((objects_axis[i][2])))) bndbox.appendChild(x1) y1 = doc.createElement('y1') y1.appendChild(doc.createTextNode(str((objects_axis[i][3])))) bndbox.appendChild(y1) x2 = doc.createElement('x2') x2.appendChild(doc.createTextNode(str((objects_axis[i][4])))) bndbox.appendChild(x2) y2 = doc.createElement('y2') y2.appendChild(doc.createTextNode(str((objects_axis[i][5])))) bndbox.appendChild(y2) x3 = doc.createElement('x3') x3.appendChild(doc.createTextNode(str((objects_axis[i][6])))) bndbox.appendChild(x3) y3 = doc.createElement('y3') y3.appendChild(doc.createTextNode(str((objects_axis[i][7])))) bndbox.appendChild(y3) f = open(save_path, 'w') f.write(doc.toprettyxml(indent='')) f.close()
def create_igv_session_annot(genome, uuids, annot_uuids=None, samp_file=None): """Creates session file for selected file uuids, returns newly created filestore uuid :param genome: Genome to be used in session file i.e. hg18, dm3 :type genome: string. :param uuids: Array of UUIDs to be used :type uuids: array. :param uuids: Host URL i.e. 127.0.0.1:8000 :type uuids: string """ # Create IGV Session file and put into Filestore """ http://www.postneo.com/projects/pyxml/ <?xml version="1.0" encoding="UTF-8"?> <Global genome="hg18" locus="EGFR" version="3"> <Resources> <Resource name="RNA Genes" path="http://www.broadinstitute.org/igvdata/tcga/gbm/GBM_batch1-8_level3_exp.txt.recentered.080820.gct.tdf"/> <Resource name="RNA Genes" path="http://www.broadinstitute.org/igvdata/annotations/hg18/rna_genes.bed"/> <Resource name="sno/miRNA" path="http://www.broadinstitute.org/igvdata/tcga/gbm/Sample_info.txt"/> </Resources> </Global> """ # Create the minidom document doc = Document() # Create the <wml> base element xml = doc.createElement("Global") xml.setAttribute("genome", genome) xml.setAttribute("locus", "All") xml.setAttribute("version", "4") doc.appendChild(xml) # Add Resources xml_resources = doc.createElement("Resources") xml.appendChild(xml_resources) # adding selected samples to xml file add_igv_resource(uuids["node_uuid"], xml_resources, doc) if annot_uuids: # adding selected samples to xml file add_igv_resource(annot_uuids["node_uuid"], xml_resources, doc) # adds sample information file to IGV session file if samp_file: # <Resource name="Sample Information" # path="http://igv.broadinstitute.org/data/hg18/tcga/gbm/gbmsubtypes/sampleTable.txt.gz"/> # creates Resource element res = doc.createElement("Resource") res.setAttribute("name", "Sample Information") res.setAttribute("path", samp_file) xml_resources.appendChild(res) # <HiddenAttributes> # <Attribute name="DATA FILE"/> # <Attribute name="Linking_id"/> # <Attribute name="DATA TYPE"/> # </HiddenAttributes> # Adding parameters to hide basic unnecessary sample info hidden_attr = doc.createElement("HiddenAttributes") xml.appendChild(hidden_attr) attr = doc.createElement("Attribute") attr.setAttribute("name", "DATA FILE") hidden_attr.appendChild(attr) attr = doc.createElement("Attribute") attr.setAttribute("name", "Linking_id") hidden_attr.appendChild(attr) attr = doc.createElement("Attribute") attr.setAttribute("name", "DATA TYPE") hidden_attr.appendChild(attr) # Creating temp file to enter into file_store tempfilename = tempfile.NamedTemporaryFile(delete=False) tempfilename.write(doc.toprettyxml(indent=" ")) tempfilename.close() # getting file_store_uuid filestore_uuid = create(tempfilename.name, filetype="xml") filestore_item = import_file(filestore_uuid, refresh=True) # file to rename temp_name = filestore_item.datafile.name.split('/') temp_name = temp_name[len(temp_name) - 1] + '.xml' # rename file by way of file_store filestore_item = rename(filestore_uuid, temp_name) # delete temp file os.unlink(tempfilename.name) # Url for session file sessionfile_url = get_full_url(filestore_item.get_datafile_url()) # IGV url for automatic launch of Java Webstart igv_url = "http://www.broadinstitute.org/igv/projects/current/igv.php" \ "?sessionURL=" + sessionfile_url return igv_url
def generate_xml(name, split_lines, img_size, class_ind, img_path): doc = Document() # 创建DOM文档对象 annotation = doc.createElement('annotation') doc.appendChild(annotation) title = doc.createElement('folder') title_text = doc.createTextNode('unnormalknife') title.appendChild(title_text) annotation.appendChild(title) img_name = name + '.jpg' title = doc.createElement('filename') title_text = doc.createTextNode(img_name) title.appendChild(title_text) annotation.appendChild(title) title = doc.createElement('path') title_text = doc.createTextNode(img_path) title.appendChild(title_text) annotation.appendChild(title) source = doc.createElement('source') annotation.appendChild(source) title = doc.createElement('database') title_text = doc.createTextNode('My database') title.appendChild(title_text) source.appendChild(title) title = doc.createElement('annotation') title_text = doc.createTextNode('STLX') title.appendChild(title_text) source.appendChild(title) size = doc.createElement('size') annotation.appendChild(size) title = doc.createElement('width') title_text = doc.createTextNode(str(img_size[1])) title.appendChild(title_text) size.appendChild(title) title = doc.createElement('height') title_text = doc.createTextNode(str(img_size[0])) title.appendChild(title_text) size.appendChild(title) title = doc.createElement('depth') title_text = doc.createTextNode(str(img_size[2])) title.appendChild(title_text) size.appendChild(title) # segmented = doc.createElement('segmented') # title_text = doc.createTextNode('0') # segmented.appendChild(title_text) # annotation.appendChild(segmented) title = doc.createElement('segmented') title_text = doc.createTextNode('0') title.appendChild(title_text) annotation.appendChild(title) for split_line in split_lines: line = split_line.strip().split() print('line:', line) if int(line[0]) in class_ind: # for fusion image w = int(float(line[3]) * img_size[1]) h = int(float(line[4]) * img_size[0]) xmin = int(float(line[1]) * img_size[1]) ymin = int(float(line[2]) * img_size[0]) xmax = xmin + w ymax = ymin + h # for single item img # xmin = line[1] # ymin = line[2] # xmax = line[3] # ymax = line[4] object = doc.createElement('object') annotation.appendChild(object) title = doc.createElement('name') title_text = doc.createTextNode(class_dict[int(line[0])]) title.appendChild(title_text) object.appendChild(title) title = doc.createElement('pose') title_text = doc.createTextNode('Unspecified') title.appendChild(title_text) object.appendChild(title) title = doc.createElement('truncated') title_text = doc.createTextNode('0') title.appendChild(title_text) object.appendChild(title) title = doc.createElement('difficult') title_text = doc.createTextNode('0') title.appendChild(title_text) object.appendChild(title) bndbox = doc.createElement('bndbox') object.appendChild(bndbox) title = doc.createElement('xmin') title_text = doc.createTextNode(str(int(xmin))) title.appendChild(title_text) bndbox.appendChild(title) title = doc.createElement('ymin') title_text = doc.createTextNode(str(int(ymin))) title.appendChild(title_text) bndbox.appendChild(title) title = doc.createElement('xmax') title_text = doc.createTextNode(str(int(xmax))) title.appendChild(title_text) bndbox.appendChild(title) title = doc.createElement('ymax') title_text = doc.createTextNode(str(int(ymax))) title.appendChild(title_text) bndbox.appendChild(title) # 将DOM对象doc写入文件 f = open('/var/samps/VOC2022/Annotations/unnormalknife/' + name + '.xml', 'w') f.write(doc.toprettyxml(indent='')) f.close()
def writeDocument(sourceDataset, targetDataset, xmlFileName): desc = arcpy.Describe(sourceDataset) descT = arcpy.Describe(targetDataset) gzSupport.addMessage(sourceDataset) xmlDoc = Document() root = xmlDoc.createElement('Gizinta') xmlDoc.appendChild(root) root.setAttribute("logTableName", 'gzLog') root.setAttribute("errorTableName", 'gzError') root.setAttribute("version", '2013.1') root.setAttribute("xmlns:gizinta", 'http://gizinta.com') extract = xmlDoc.createElement("Extract") root.appendChild(extract) dataElementName = getExtractElementName(desc, sourceDataset) source = xmlDoc.createElement(dataElementName) sourceName = getName(desc, sourceDataset) targetName = getName(descT, targetDataset) setDefaultProperties(source, dataElementName, sourceDataset, sourceName, targetName) where = xmlDoc.createElement("WhereClause") source.appendChild(where) extract.appendChild(source) transform = xmlDoc.createElement("Transform") root.appendChild(transform) dataset = xmlDoc.createElement("Dataset") transform.appendChild(dataset) dataset.setAttribute("name", targetName) dataset.setAttribute("qa", "CheckFields,CheckGeometry") dataset.setAttribute("sourceIDField", "") dataset.setAttribute("sourceNameField", "") fields = getFields(descT, targetDataset) sourceFields = getFields(desc, sourceDataset) sourceNames = [ field.name[field.name.rfind(".") + 1:] for field in sourceFields ] i = 0 try: for field in fields: fNode = xmlDoc.createElement("Field") dataset.appendChild(fNode) fieldName = field.name[field.name.rfind(".") + 1:] if fieldName in sourceNames: addFieldElement(xmlDoc, fNode, "SourceName", fieldName) else: addFieldElement(xmlDoc, fNode, "SourceName", "*" + fieldName + "*") addFieldElement(xmlDoc, fNode, "TargetName", fieldName) addFieldElement(xmlDoc, fNode, "Method", "Copy") addFieldElement(xmlDoc, fNode, "FieldType", field.type) addFieldElement(xmlDoc, fNode, "FieldLength", str(field.length)) i += 1 setSourceFields(xmlDoc, dataset, sourceNames) # Should add a template section for value maps, maybe write domains... xmlStr = xmlDoc.toprettyxml() uglyXml = xmlDoc.toprettyxml(indent=' ') text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL) prettyXml = text_re.sub('>\g<1></', uglyXml) fHandle = open(xmlFileName, 'w') fHandle.write(prettyXml) fHandle.close() except: gzSupport.showTraceback() xmlStr = "" return xmlStr