def to_html(self): dom = xml.dom.getDOMImplementation() doc = dom.createDocument(None, None, None) html = doc.createElement('html') head = doc.createElement('head') title = doc.createElement('title') title_text = doc.createTextNode('PPC1 2013 timetable') title.appendChild(title_text) head.appendChild(title) html.appendChild(head) body = doc.createElement('body') table = doc.createElement('table border=1') head_row = doc.createElement('tr') _add_td(doc, head_row, 'Time', bold=True) _add_td(doc, head_row, 'Code', bold=True) _add_td(doc, head_row, 'Name', bold=True) _add_td(doc, head_row, 'Coordinator', bold=True) _add_td(doc, head_row, 'Location', bold=True) _add_td(doc, head_row, 'Tutorial groups (click to see all)', bold=True) _add_td(doc, head_row, 'Skills groups (click to see all)', bold=True) table.appendChild(head_row) for w in self.weeks: for r in w.to_html(doc): table.appendChild(r) body.appendChild(table) html.appendChild(body) doc.appendChild(html) return doc.toprettyxml()
def create_document(self): """uses xml.dom to create document with correct doctype""" dom = xml.dom.getDOMImplementation() tmxdoctype = dom.createDocumentType("tmx", None, "tmx14.dtd") tmx = dom.createDocument("http://www.lisa.org/tmx14", "tmx", tmxdoctype ) return tmx
def create_document(self): """uses xml.dom to create document with correct doctype""" dom = xml.dom.getDOMImplementation() tmxdoctype = dom.createDocumentType("tmx", None, "tmx14.dtd") tmx = dom.createDocument("http://www.lisa.org/tmx14", "tmx", tmxdoctype) return tmx
def Save(self, ProjPath, Backup=False): """Save project in XML-project file""" # simple DOM realisation dom = xml.dom.minidom.getDOMImplementation() # "Game" - is root element # "IGv1" means that XML document is Instead Game of version 1 DocType = dom.createDocumentType("IGv1", None, None) tree = dom.createDocument(None, "Game", DocType) root = tree.documentElement # saving settings Settings = tree.createElement("Settings") Settings.setAttribute("Name", self.Game.Settings["Name"]) Settings.setAttribute("Version", self.Game.Settings["Version"]) Settings.setAttribute("Author", self.Game.Settings["Author"]) Settings.setAttribute("Description", self.Game.Settings["Description"]) root.appendChild(Settings) # Game Items section Items = tree.createElement("Items") root.appendChild(Items) # xml element presenting Item looks like this # <Item Type="Scene" Name="house">text of the scene</Item> temp = ((SCENE, "Scene"), (XSCENE, "XScene"), (OBJECT, "Object"), (DIALOG, "Dialog"), (FUNCTION, "Function")) for i in range(len(temp)): for name in self.Game.GetNames(temp[i][0], True, True): element = tree.createElement("Item") element.setAttribute("Type", temp[i][1]) element.setAttribute("Name", name) Code = self.Game.GetCode(name) if Code == "": # Empty text data is not allowed in XML! Code = " " code = tree.createTextNode(Code) element.appendChild(code) Items.appendChild(element) # make backup if Backup: try: shutil.copyfile(ProjPath, ProjPath + "~") except: pass # writing project file file = open(ProjPath, "tw+", encoding="utf-8") # xml_code = tree.toprettyxml(indent = " "*8) # print(xml_code) xml_code = tree.toxml() file.write(xml_code)
def write_results_xml(self, fn, stdout=False): try: f = open(TEST_RESULTS, "w") except IOError: print "Failed to open test results output file: %s" % TEST_RESULTS return except: print "Unexpected error: %s" % sys.exc_info()[0] return dom = xml.dom.getDOMImplementation() doc = dom.createDocument(None, "testsuite", None) ts = doc.documentElement ts.setAttribute("errors", "0") ts.setAttribute("tests", str(self.total_count)) ts.setAttribute("time", "%.2f" % self.total_time) ts.setAttribute("failures", str(self.total_failures)) ts.setAttribute("name", "AsteriskTestSuite") if self.options.dry_run: ts.setAttribute("dry-run", str(self.total_count)) for t in self.tests: if t.did_run is False: continue tc = doc.createElement("testcase") ts.appendChild(tc) tc.setAttribute("time", "%.2f" % t.time) tc.setAttribute("name", t.test_name) if t.passed: continue failure = doc.createElement("failure") failure.appendChild( doc.createTextNode( self.__strip_illegal_xml_chars(t.failure_message))) tc.appendChild(failure) doc.writexml(f, addindent=" ", newl="\n", encoding="utf-8") f.close() if stdout: print doc.toprettyxml(" ", encoding="utf-8")
def generateCrateXML(crates): dom = xml.dom.getDOMImplementation() document = dom.createDocument(None, None, None) ncrates = document.createElement('crates') document.appendChild(ncrates) for cratename in crates: ncrate = document.createElement('crate') ncrates.appendChild(ncrate) ncrate.setAttribute('name', cratename) for track in crates[cratename]: ntrack = document.createElement('track') ncrate.appendChild(ntrack) for key in track.keys(): ntrack.setAttribute(key, unicode(track[key])) return document.toxml()
def write_results_xml(self, fn, stdout=False): try: f = open(TEST_RESULTS, "w") except IOError: print "Failed to open test results output file: %s" % TEST_RESULTS return except: print "Unexpected error: %s" % sys.exc_info()[0] return dom = xml.dom.getDOMImplementation() doc = dom.createDocument(None, "testsuite", None) ts = doc.documentElement ts.setAttribute("errors", "0") ts.setAttribute("tests", str(self.total_count)) ts.setAttribute("time", "%.2f" % self.total_time) ts.setAttribute("failures", str(self.total_failures)) ts.setAttribute("name", "AsteriskTestSuite") if self.options.dry_run: ts.setAttribute("dry-run", str(self.total_count)) for t in self.tests: if t.did_run is False: continue tc = doc.createElement("testcase") ts.appendChild(tc) tc.setAttribute("time", "%.2f" % t.time) tc.setAttribute("name", t.test_name) if t.passed: continue failure = doc.createElement("failure") failure.appendChild(doc.createTextNode( self.__strip_illegal_xml_chars(t.failure_message))) tc.appendChild(failure) doc.writexml(f, addindent=" ", newl="\n", encoding="utf-8") f.close() if stdout: print doc.toprettyxml(" ", encoding="utf-8")
def Write_xls2xml(filepath, element, comment, savepath): try: df = pd.read_excel(filepath, header=None) # ,index_col= 0) except IOError: print("Cannot open file:\"", filepath, "\",please check!") exit() str1 = "[\n\t[" #调整格式以符合题意 for i in range(3): for j in range(3): str1 = str1 + str(df.ix[i][j]) if j < 2: str1 = str1 + ", " if j == 2 and i != 2: str1 = str1 + "],\n\t[" str1 = str1 + "]\n ]" dom = xml.dom.getDOMImplementation() #创建文档对象,文档对象用于创建各种节点。 doc = dom.createDocument(None, "root", None) #创建根节点 root = doc.documentElement students = doc.createElement(element) #创建元素 root.appendChild(students) comment = doc.createComment(comment) #创建comment students.appendChild(comment) nameT = doc.createTextNode(str1) students.appendChild(nameT) xmlfile = open(savepath, 'w') doc.writexml(xmlfile, addindent=' ', newl='\n', encoding='utf-8') #写入的文件有转义字符",所以下一步需要重新读取并整理数据 xmlfile.close() xml_file = open(savepath) #重新读取xml并转换转义字符 try: xml_content = xml_file.read() # finally: xml_file.close() xml_content = xml_content.replace(""", "\"") #替换转义字符 output = open(savepath, 'w') output.write(xml_content) output.close() win32api.ShellExecute(0, 'open', 'notepad.exe', savepath, '', 1) # 打开文件
def export_xml_dom(self, filename): dom = xml.dom.minidom.getDOMImplementation() tree = dom.createDocument(None, 'incidents', None) root = tree.documentElement for incident in self.values(): element = tree.createElement('incident') for attribute, value in ( ("report_id", incident.report_id), ("date", incident.date.isoformat()), ("aircraft_id", incident.aircraft_id), ("aircraft_type", incident.aircraft_type), ("pilot_percent_hours_on_type", str(incident.pilot_percent_hours_on_type)), ("pilot_total_hours", str(incident.pilot_total_hours)), ("midair", str(int(incident.midair)))): element.setAttribute(attribute, value) for name, text in (('airport', incident.airport), ('narrative', incident.narrative)): text_element = tree.createTextNode(text) name_element = tree.createElement(name) name_element.appendChild(text_element) element.appendChild(name_element) root.appendChild(element) fh = None try: fh = open(filename, 'w', encoding='utf-8') tree.writexml(fh) return True except (IOError, EnvironmentError, xml.parsers.expat.ExpatError) as save_err: print('{} error: {}'.format(os.path.basename(sys.argv[0]), save_err)) return False finally: if fh: fh.close()
raise RuntimeError("can't parse the field: '%s'" % field_fragment) all_structs[st_name] = Struct(fields=fields) # For each struct, decide the primary peripheral struct_pri_peripheral: Dict[str, str] = {} for peripheral in all_peripherals_list: st_name = peripheral.st_name if st_name not in struct_pri_peripheral: struct_pri_peripheral[st_name] = peripheral.name # Generate SVD dom = xml.dom.getDOMImplementation('minidom') svd_doc = dom.createDocument(xml.dom.EMPTY_NAMESPACE, 'device', None) svd_root = svd_doc.documentElement svd_root.setAttribute('schemaVersion', '1.1') svd_root.setAttribute('xmlns:xs', 'http://www.w3.org/2001/XMLSchema-instance') svd_root.setAttribute('xs:noNamespaceSchemaLocation', 'CMSIS-SVD.xsd') svd_root.appendChild(svd_doc.createComment(""" Do not modify! This file was automatically @generated by mksvd.py. """)) def add_element(parent, name: str, value: str): e = svd_doc.createElement(name) e.appendChild(svd_doc.createTextNode(value)) parent.appendChild(e)
def main(): # Specify the command line arguments and parse them parser = argparse.ArgumentParser(description='convert a SHP file to a KML documents') parser.add_argument('shp', metavar='FILENAME.shp', type=str, nargs=1, help='a SHP file to parse') parser.add_argument('-d, --dbf', metavar='FILENAME.dbf', type=str, nargs='?', dest='dbf', help='a database file to read associated shape records from', default=None) args = parser.parse_args() # Load SHP and (optionally) DBF file shp = open(args.shp[0]) dbf = open(args.dbf) if args.dbf is not None else None # Create a file id based on the name of the file file_id, _ = os.path.splitext(os.path.basename(args.shp[0])) # Load the shape file sf = shapefile.Reader(shp=shp, dbf=dbf) log.info('%s: loaded %s shapes' % (args.shp[0], len(sf.shapes()))) # Create a document to hold the KML dom = xml.dom.getDOMImplementation() kml_doc = dom.createDocument(kml_ns, 'kml', None) kml = kml_doc.documentElement kml.setAttribute('xmlns', kml_ns) # Create the containing Document node document = kml_doc.createElement('Document') document.setAttribute('id', file_id) kml.appendChild(document) # Set up the style style = kml_doc.createElement('Style') style.setAttribute('id', 'shape') document.appendChild(style) # Create a line style with specified width and color line_style = kml_doc.createElement('LineStyle') style.appendChild(line_style) width = kml_doc.createElement('width') width.appendChild(kml_doc.createTextNode(str(2))) line_style.appendChild(width) color = kml_doc.createElement('color') color.appendChild(kml_doc.createTextNode('ff0000dd')) line_style.appendChild(color) # Get a list of shapes and, if present, records. If no DBF file is # provided, generate a list of None records. shapes = sf.shapes() records = sf.records() if dbf is not None else ([None,] * len(shapes)) fields = sf.fields if dbf is not None else [] # Convert each shape in the file for idx, sr_pair in enumerate(zip(shapes, records)): shape, record = sr_pair id_str = 'shape_%i' % idx name = 'shape %i' % idx pm = shape_to_placemark(kml_doc, shape, id_str, name = name, record = record, fields = fields[1:]) document.appendChild(pm) # Extend the placemark with styling style_url = kml_doc.createElement('styleUrl') style_url.appendChild(kml_doc.createTextNode('#shape')) pm.appendChild(style_url) # Output the XML print(kml_doc.toprettyxml(indent=' '))
def main(argv=None): if argv is None: args = sys.argv usage = "Usage: ./runtests.py [options]" parser = optparse.OptionParser(usage=usage) parser.add_option("-c", "--cleanup", action="store_true", dest="cleanup", default=False, help="Cleanup tmp directory after each successful test") parser.add_option("-d", "--dry-run", action="store_true", dest="dry_run", default=False, help="Only show which tests would be run.") parser.add_option("-g", "--tag", action="append", dest="tags", help="Specify one or more tags to select a subset of tests.") parser.add_option("-k", "--keep-core", action="store_true", dest="keep_core", default=False, help="Archive the 'core' file if Asterisk crashes.") parser.add_option("-l", "--list-tests", action="store_true", dest="list_tests", default=False, help="List tests instead of running them.") parser.add_option("-L", "--list-tags", action="store_true", dest="list_tags", default=False, help="List available tags") parser.add_option("-s", "--syslog", action="store_true", dest="syslog", default=False, help="Log test start/stop to syslog") parser.add_option("-t", "--test", action="append", default=[], dest="tests", help="Run a single specified test (directory) instead " "of all tests. May be specified more than once.") parser.add_option("-v", "--version", dest="version", default=None, help="Specify the version of Asterisk rather then detecting it.") parser.add_option("-V", "--valgrind", action="store_true", dest="valgrind", default=False, help="Run Asterisk under Valgrind") parser.add_option("--email-on-crash", action="store_true", dest="email_on_crash", default=False, help="Send email on crash with a backtrace. See " "crash-mail-config.yaml.sample for details.") parser.add_option("--number", metavar="int", type=int, dest="number", default=1, help="Number of times to run the test suite. If a value of " "-1 is provided, the test suite will loop forever.") parser.add_option("--random-order", action="store_true", dest="randomorder", default=False, help="Shuffle the tests so they are run in random order") parser.add_option("--timeout", metavar='int', type=int, dest="timeout", default=-1, help="Abort test after n seconds of no output.") (options, args) = parser.parse_args(argv) # Install a signal handler for USR1/TERM, and use it to bail out of running # any remaining tests signal.signal(signal.SIGUSR1, handle_usr1) signal.signal(signal.SIGTERM, handle_term) ast_version = AsteriskVersion(default=options.version) if options.list_tests or options.list_tags: test_suite = TestSuite(ast_version, options) if options.list_tests: test_suite.list_tests() if options.list_tags: test_suite.list_tags() return 0 if options.timeout > 0: options.timeout *= 1000 # Ensure that there's a trailing '/' in the tests specified with -t for i, test in enumerate(options.tests): if not test.endswith('/'): options.tests[i] = test + '/' if options.valgrind: if not ET: print "python lxml module not loaded, text summaries " \ "from valgrind will not be produced.\n" os.environ["VALGRIND_ENABLE"] = "true" dom = xml.dom.getDOMImplementation() doc = dom.createDocument(None, "testsuites", None) continue_forever = True if options.number < 0 else False iteration = 0 if options.syslog: syslog.openlog('AsteriskTestsuite', syslog.LOG_PID) while ((iteration < options.number or continue_forever) and not abandon_test_suite): test_suite = TestSuite(ast_version, options) running_str = "Running tests for Asterisk {0} (run {1})...\n".format( str(ast_version).strip('\n'), iteration + 1) print running_str if options.syslog: syslog.syslog(running_str) test_suite.run() test_suite.write_results_xml(doc, doc.documentElement) # If exactly one test was requested, then skip the summary. if len(test_suite.tests) != 1: print "\n=== TEST RESULTS ===\n" print "PATH: %s\n" % os.getenv("PATH") for t in test_suite.tests: sys.stdout.write("--> %s --- " % t.test_name) if t.did_run is False: print "SKIPPED" for d in t.test_config.deps: print " --> Dependency: %s -- Met: %s" % (d.name, str(d.met)) if options.tags: for t in t.test_config.tags: print " --> Tag: %s -- Met: %s" % (t, str(t in options.tags)) continue if t.passed is True: print "PASSED" else: print "FAILED" iteration += 1 if ref_debug_is_enabled: test_suite.generate_refleaks_summary() try: with open(TEST_RESULTS, "w") as f: doc.writexml(f, addindent=" ", newl="\n", encoding="utf-8") except IOError: print "Failed to open test results output file: %s" % TEST_RESULTS except: print "Unexpected error: %s" % sys.exc_info()[0] print "\n" print doc.toprettyxml(" ", encoding="utf-8") if options.syslog: syslog.syslog("All tests concluded") syslog.closelog() return test_suite.total_failures
def main(argv=None): if argv is None: args = sys.argv global abandon_test_suite usage = "Usage: ./runtests.py [options]" parser = optparse.OptionParser(usage=usage) parser.add_option("-c", "--cleanup", action="store_true", dest="cleanup", default=False, help="Cleanup tmp directory after each successful test") parser.add_option("-d", "--dry-run", action="store_true", dest="dry_run", default=False, help="Only show which tests would be run.") parser.add_option("-g", "--tag", action="append", dest="tags", help="Specify one or more tags to select a subset of tests.") parser.add_option("-G", "--skip-tag", action="append", dest="skip_tags", help="Specify one or more tags to ignore a subset of tests.") parser.add_option("-k", "--keep-core", action="store_true", dest="keep_core", default=False, help="Archive the 'core' file if Asterisk crashes.") parser.add_option("-l", "--list-tests", action="store_true", dest="list_tests", default=False, help="List tests instead of running them.") parser.add_option("--list-terse", action="store_true", dest="list_terse", default=False, help="List tests in 'nnnn A testname [ unmet_dependency[,unmet_dependency]...]' format " "where 'nnnn' = number, 'A' = 'S':Skipped, 'D':Dependency not met, 'E':Enabled, " "'unmet_dependency': A CSV list of unmet dependencies, if any" ) parser.add_option("-L", "--list-tags", action="store_true", dest="list_tags", default=False, help="List available tags") parser.add_option("-s", "--syslog", action="store_true", dest="syslog", default=False, help="Log test start/stop to syslog") parser.add_option("-t", "--test", action="append", default=[], dest="tests", help="Run a single specified test (directory) instead " "of all tests. May be specified more than once.") parser.add_option("--test-regex", action="append", default=[], dest="tests_regex", help="Run tests matching the supplied regex." "May be specified more than once.") parser.add_option("-T", "--skip-test-regex", action="append", default=[], dest="skip_tests_regex", help="Exclude tests based on regex. " "May be specified more than once.") parser.add_option("-v", "--version", dest="version", default=None, help="Specify the version of Asterisk rather then detecting it.") parser.add_option("-V", "--valgrind", action="store_true", dest="valgrind", default=False, help="Run Asterisk under Valgrind") parser.add_option("--email-on-crash", action="store_true", dest="email_on_crash", default=False, help="Send email on crash with a backtrace. See " "crash-mail-config.yaml.sample for details.") parser.add_option("--number", metavar="int", type=int, dest="number", default=1, help="Number of times to run the test suite. If a value of " "-1 is provided, the test suite will loop forever.") parser.add_option("--random-order", action="store_true", dest="randomorder", default=False, help="Shuffle the tests so they are run in random order") parser.add_option("--timeout", metavar='int', type=int, dest="timeout", default=-1, help="Abort test after n seconds of no output.") parser.add_option("--stop-on-error", action="store_true", dest="stop_on_error", default=False, help="Stops the testsuite when a test fails.") parser.add_option("--pcap", action="store_true", dest="pcap", default=False, help="Capture packets. Output will be in " " the test's log directory as packet.pcap.") parser.add_option("--keep-full-logs", action="store_true", dest="keep_full_logs", default=False, help="Keep full logs even if test passes.") (options, args) = parser.parse_args(argv) # Install a signal handler for USR1/TERM, and use it to bail out of running # any remaining tests signal.signal(signal.SIGUSR1, handle_usr1) signal.signal(signal.SIGTERM, handle_term) if options.list_tests or options.list_tags or options.list_terse : test_suite = TestSuite(options) if options.list_tests: test_suite.list_tests() if options.list_tags: test_suite.list_tags() if options.list_terse: test_suite.list_terse() return 0 if options.timeout > 0: options.timeout *= 1000 # Ensure that there's a trailing '/' in the tests specified with -t for i, test in enumerate(options.tests): if "/" not in test and "." in test: options.tests[i] = "tests/" + test.replace(".", "/") + "/" elif not test.endswith('/'): options.tests[i] = test + '/' if options.valgrind: if not ET: print("python lxml module not loaded, text summaries " "from valgrind will not be produced.\n") os.environ["VALGRIND_ENABLE"] = "true" dom = xml.dom.getDOMImplementation() doc = dom.createDocument(None, "testsuites", None) continue_forever = True if options.number < 0 else False iteration = 0 if options.syslog: syslog.openlog('AsteriskTestsuite', syslog.LOG_PID) while ((iteration < options.number or continue_forever) and not abandon_test_suite): test_suite = TestSuite(options) running_str = "Running tests for Asterisk (run {0} of {1})...\n".format( iteration + 1, options.number) print(running_str) if options.syslog: syslog.syslog(running_str) test_suite.run() test_suite.write_results_xml(doc, doc.documentElement) # If exactly one test was requested, then skip the summary. if len(test_suite.tests) != 1: print("\n=== TEST RESULTS ===\n") print("PATH: %s\n" % os.getenv("PATH")) for t in test_suite.tests: sys.stdout.write("--> %s --- " % t.test_name) if t.did_run is False: print("SKIPPED") for d in t.test_config.deps: print(" --> Dependency: %s -- Met: %s" % (d.name, str(d.met))) if options.tags: for t in t.test_config.tags: print(" --> Tag: %s -- Met: %s" % (t, str(t in options.tags))) continue if t.passed is True: print("PASSED") else: print("FAILED") iteration += 1 if ref_debug_is_enabled: test_suite.generate_refleaks_summary() try: with open(TEST_RESULTS, "w") as f: doc.writexml(f, addindent=" ", newl="\n", encoding="utf-8") except IOError: print("Failed to open test results output file: %s" % TEST_RESULTS) except: print("Unexpected error: %s" % sys.exc_info()[0]) print("\n") print(doc.toprettyxml(" ", encoding="utf-8").decode('utf-8', 'ignore')) if options.syslog: syslog.syslog("All tests concluded") syslog.closelog() return test_suite.total_failures
def createDocElementFromName(self, docname, dtd_filename): dom = xml.dom.minidom.getDOMImplementation() type = dom.createDocumentType(docname, None, dtd_filename) doc = dom.createDocument(None, docname, type) return doc
def main(): # Specify the command line arguments and parse them parser = argparse.ArgumentParser( description='convert a SHP file to a KML documents') parser.add_argument('shp', metavar='FILENAME.shp', type=str, nargs=1, help='a SHP file to parse') parser.add_argument( '-d, --dbf', metavar='FILENAME.dbf', type=str, nargs='?', dest='dbf', help='a database file to read associated shape records from', default=None) args = parser.parse_args() # Load SHP and (optionally) DBF file shp = open(args.shp[0]) dbf = open(args.dbf) if args.dbf is not None else None # Create a file id based on the name of the file file_id, _ = os.path.splitext(os.path.basename(args.shp[0])) # Load the shape file sf = shapefile.Reader(shp=shp, dbf=dbf) log.info('%s: loaded %s shapes' % (args.shp[0], len(sf.shapes()))) # Create a document to hold the KML dom = xml.dom.getDOMImplementation() kml_doc = dom.createDocument(kml_ns, 'kml', None) kml = kml_doc.documentElement kml.setAttribute('xmlns', kml_ns) # Create the containing Document node document = kml_doc.createElement('Document') document.setAttribute('id', file_id) kml.appendChild(document) # Set up the style style = kml_doc.createElement('Style') style.setAttribute('id', 'shape') document.appendChild(style) # Create a line style with specified width and color line_style = kml_doc.createElement('LineStyle') style.appendChild(line_style) width = kml_doc.createElement('width') width.appendChild(kml_doc.createTextNode(str(2))) line_style.appendChild(width) color = kml_doc.createElement('color') color.appendChild(kml_doc.createTextNode('ff0000dd')) line_style.appendChild(color) # Get a list of shapes and, if present, records. If no DBF file is # provided, generate a list of None records. shapes = sf.shapes() records = sf.records() if dbf is not None else ([ None, ] * len(shapes)) fields = sf.fields if dbf is not None else [] # Convert each shape in the file for idx, sr_pair in enumerate(zip(shapes, records)): shape, record = sr_pair id_str = 'shape_%i' % idx name = 'shape %i' % idx pm = shape_to_placemark(kml_doc, shape, id_str, name=name, record=record, fields=fields[1:]) document.appendChild(pm) # Extend the placemark with styling style_url = kml_doc.createElement('styleUrl') style_url.appendChild(kml_doc.createTextNode('#shape')) pm.appendChild(style_url) # Output the XML print(kml_doc.toprettyxml(indent=' '))
def coco2voc(self, coco_json, cat_id=-1, object365=False, separate_storing=True, save_path="", database="FoodDection"): """ Args: coco_json: coco json标注文件 cat_id: 类别id,,-1表示提取所有类别,字符串表示某一大类 object365: object365标注文件 separate_storing: save_path:各个类别是否分别存放 database:数据库名称 Returns: """ image_info, cat_info, anno_info, categries = self.read_coco(coco_json, cat_id) if not \ object365 else self.read_object365(coco_json, cat_id) save_path = save_path if save_path else os.path.split(coco_json)[0] folder = os.path.split(save_path)[1] if type(cat_id) == str and separate_storing and not object365: sub_cats = [ j["name"].replace(" ", "_") for j in categries if j["supercategory"] == cat_id ] elif object365: sub_cats = [ i.replace(" ", "_") for i in read_txt(cat_id, return_list=True) ] else: sub_cats = [] for image_id, image in image_info.items(): annos = anno_info[image_id] dom = xml.dom.getDOMImplementation() doc = dom.createDocument(None, "annotation", None) # 创建根节点 root_node = doc.documentElement # folder节点 self.createChildNode(doc, "folder", folder, root_node) # filename节点 self.createChildNode(doc, "filename", image['file_name'], root_node) # path节点 self.createChildNode(doc, "path", "./" + image["file_name"], root_node) # source节点 source_node = doc.createElement("source") # source子节点 self.createChildNode(doc, "database", database, source_node) root_node.appendChild(source_node) # size节点 size_node = doc.createElement("size") self.createChildNode(doc, "width", str(image["width"]), size_node) self.createChildNode(doc, "height", str(image["height"]), size_node) self.createChildNode(doc, "depth", str(image.get("depth", 3)), size_node) root_node.appendChild(size_node) # segmented节点 self.createChildNode(doc, "segmented", self.segmented, root_node) cat_name = "" for one in annos: object_node = self.createObjectNode(doc, one) root_node.appendChild(object_node) if type(cat_id) == str and (one["cat_name"] in sub_cats): cat_name = one["cat_name"].replace(" ", "_") # 写入文件 xml_filename = image["file_name"].strip(".jpg") + ".xml" if separate_storing and type(cat_id) == str: path = save_path + "/" + cat_name if cat_name == "": input("ddd") os.makedirs(path, exist_ok=True) else: path = save_path xml_filename = os.path.join(path, xml_filename) self.writeXMLFile(doc, xml_filename)
import win32api filepath = "d:/python_project/ex_0014/data/Student.xls" df = pd.read_excel(filepath, header=None) #,index_col= 0) #df = dict(df) #df = json.dumps(df, ensure_ascii=False, indent=1) #df = df.to_json(force_ascii = False,orient = 'split') str1 = "{\n\t" for i in range(3): str1 = str1 + str(df.ix[i].values) str1 = str1 + "\n\t" str1 = str1.replace("[", "\"") #str1 = str1.replace(" ",",") str1 = str1.replace(" '", "\" : [\"") str1 = str1.replace("'", "\"") str1 = str1 + "\n }" #str1 = str1.replace(" ",",") #str1 = "{\n\t" + str1 print(str1) dom = xml.dom.getDOMImplementation() #创建文档对象,文档对象用于创建各种节点。 doc = dom.createDocument(None, "root", None) root = doc.documentElement students = doc.createElement('students') root.appendChild(students) comment = doc.createComment('\n\t学生信息表\n\t\"id\":[名字,数学,语文,英文]\n') students.appendChild(comment) nameT = doc.createTextNode(str1) students.appendChild(nameT) xmlfile = open('student.xml', 'w') doc.writexml(xmlfile, addindent=' ', newl='\n', encoding='utf-8') xmlfile.close() win32api.ShellExecute(0, 'open', 'notepad.exe', 'student.xml', '', 1) # 打开文件