def save_settings(settings_xml, xmldoc): try: outputfile = open(settings_xml, 'w') xmlpp.pprint(xmldoc.toxml(), output = outputfile, indent=2) outputfile.close() except IOError: print 'Error saving file:', settings_xml settings_restore(settings_xml)
def save_settings(settings_xml, xmldoc): try: outputfile = open(settings_xml, 'w') xmlpp.pprint(xmldoc.toxml(), output=outputfile, indent=2, width=500) outputfile.close() except IOError: print 'Error saving file:', settings_xml settings_restore(settings_xml)
def save_settings(settings_xml, xmldoc): try: dbg_log('function::save_settings', 'enter_function', 0) outputfile = open(settings_xml, 'w') xmlpp.pprint(xmldoc.toxml(), output=outputfile, indent=2) outputfile.close() except Exception, e: settings_restore(settings_xml) dbg_log('function::save_settings', 'ERROR: (' + repr(e) + ')')
def save_settings(settings_xml, xmldoc): try: dbg_log('function::save_settings', 'enter_function', 0) outputfile = open(settings_xml, 'w') xmlpp.pprint(xmldoc.toxml(), output = outputfile, indent=2) outputfile.close() except Exception, e: settings_restore(settings_xml) dbg_log('function::save_settings', 'ERROR: (' + repr(e) + ')')
def save(self, vxmldoc): try: common.dbg_log('settings::save', 'enter_function') outputfile = open(self.SettingsFile, 'w') xmlpp.pprint(vxmldoc.toxml('utf-8'), output = outputfile, indent=4) outputfile.close() common.dbg_log('settings::save', 'exit_function') except Exception, e: common.dbg_log('settings::save', 'ERROR: (' + repr(e) + ')', common.logErorr) self.restore()
def createXML(file, packages): root = ET.Element('packages') date = datetime.now().strftime("%Y-%m-%d %H:%M") root.set('date', date) # Set File Date comment = ET.Comment('Generated by python....') root.append(comment) for entry in packages: package = ET.Element('package') package.set('id', entry[0]) package.set('version', entry[1]) root.append(package) xml = "<?xml version='1.0' encoding='UTF-8'?>" + ET.tostring(root, encoding='utf-8', method='xml') outputfile = open(file, 'w') xmlpp.pprint(xml, output=outputfile) outputfile.close()
def main () : # Read file Json and get a python data structure. data = sys.stdin.read() jsondata = json.loads(data) # Root Element my document xml. root = ET.Element("papeleria") # Get Elements of XML. for x in range(len(jsondata)) : putElement(root , jsondata[x]) # Print XML Format. xmlData = ET.tostring(root , encoding="utf-8" , method="xml") xmlpp.pprint(xmlData , sys.stdout , 4 , 80)
def readfile (args) : listJson = [] data = [] root = ET.Element(u"instants") for x in sys.stdin.readlines() : # Read line by line the file and get the conversion of datetimes and # zones. if x.strip() != '' : procline(x.strip() , args , listJson , root) if args.json : print json.dumps(listJson , sort_keys = True , indent = 4) if isXML(args) : # Print XML Format. xmlData = ET.tostring(root , encoding="utf-8" , method="xml") xmlpp.pprint(xmlData , sys.stdout , 4 , 80)
def dumpXML(self, fileName, w, h): #print "Dumping ", fileName # buld tree structure exp = ET.Element('Experiment', filename=self.expName) # print exp.tag, exp.attrib run = ET.SubElement(exp, 'Run') run.attrib['subjectName'] = self.run.subjectName run.attrib['runNumber'] = self.run.runNumber run.attrib['dateTime'] = self.run.dateTime # print run.tag, run.attrib # for pt in self.gazepoints: # data = ET.SubElement(run,'GazeData') # data.attrib['Id'] = "1" # data.attrib['Time'] = "%f" % (pt.gettimestamp()) # data.attrib['Error'] = "%s" % (pt.getStatus()) # data.attrib['X'] = "%f" % (pt.at(0)) # data.attrib['Y'] = "%f" % (pt.at(1)) for fx in self.fixations: data = ET.SubElement(run, 'FixationData') data.attrib['Id'] = "1" data.attrib['Time'] = "%f" % (fx.gettimestamp()) data.attrib['FX'] = "%f" % (fx.at(0) * float(w)) data.attrib['FY'] = "%f" % (fx.at(1) * float(h)) data.attrib['Duration'] = "%f" % (fx.getDuration()) data.attrib['PercentDuration'] = "%f" % (fx.getPercentDuration()) # wrap experiment in ElementTree instance, output # this is machine-readable output, not very human-readable # tree = ET.ElementTree(exp) ## tree.write(fileName) # this is more human-readable but quite slow outfile = open(fileName, 'w') # print xmlpp.pprint(tostring(exp)) xmlpp.pprint(tostring(exp), output=outfile) outfile.close()
def outputZipContent (bytes, printer, width=80): printer("Zipped content:") rawFile = StringIO.StringIO(bytes) zipFile = zipfile.ZipFile(rawFile) i = 0 # TODO: when 2.6/3.0 is in widespread use, change to infolist # here, names might be ambiguous for filename in zipFile.namelist(): if i > 0: printer('-'*width) i += 1 printer("") printer(filename + ":") printer('-'*width) contents = zipFile.read(filename) if filename.endswith(".xml") or contents.startswith("<?xml"): wrapper = StreamWrap(printer) xmlpp.pprint(contents,wrapper,1,80) wrapper.flush() else: dumpBytes(contents) zipFile.close()
category_name = os.path.basename(cat) category_name = category_name[:-3] objs = glob.glob(cat + "/*.ply") for file_in in objs: # features get written to a .txt file for now -- PCL reader/writter doesn't handle variable length descriptos obj_name = os.path.basename(file_in) obj_name = obj_name[: -len(".ply")] if random.randint(0, 1) == 1: SubElement(scene_elm_train, "object", {"class_name": category_name, "ply_name": obj_name}) else: SubElement(scene_elm_test, "object", {"class_name": category_name, "ply_name": obj_name}) train_tree = ElementTree(info_root_train) test_tree = ElementTree(info_root_test) outputfile = open(train_file, "w") # string_train = "<xml>" + + "</xml>" xmlpp.pprint(tostring(info_root_train, "UTF-8"), outputfile) outputfile.close() outputfile = open(test_file, "w") # string_test = "<xml>" + + "</xml>" xmlpp.pprint(tostring(info_root_test, "UTF-8"), outputfile) outputfile.close() print "Done" sys.exit(0)
def main(cfgfile, config): try: config.read(cfgfile) except cp.ParsingError: parser.error("Requires a valid configuration file: %s", cfgfile) return try: cwd = os.getcwd() # # Assumption: basedir is one directory up from current directory basedir = cwd[:cwd.rfind(os.path.sep)] EADirectory = config.get('location', 'EADirectory') ReleaseDirectory = config.get('location', 'ReleaseDirectory') except cp.NoSectionError as err: print(str(err)) return EADirFullPath = os.path.join(basedir, EADirectory) ReleaseFullPath = os.path.join(basedir, ReleaseDirectory) if ord(os.path.sep) != ord('/'): EADirFullPath.replace('/', os.path.sep) ReleaseFullPath.replace('/', os.path.sep) DefaultNamespace = config.get('schema', 'defaultNamespace') # # Initialization schemaFile = config.get('schema', 'name') EASchemaFile = os.path.join(EADirFullPath, schemaFile) if not os.path.isfile(EASchemaFile): print('Missing schema file in EA directory, %s' % EASchemaFile) return # outputfile = os.path.join(ReleaseFullPath, schemaFile) nameSpaces = root = None # # Make required changes to EA schema files to be fully compliant. # Extract namespace prefixes and URIs in the EA output and check to make sure # the mandatory ones are included in the altered, changed schema # try: schemaNamespaces = dict(config.items('imports')) root, nameSpaces = parseAndGetNameSpaces(EASchemaFile, schemaNamespaces) fixImports(root, schemaNamespaces, nameSpaces) except cp.NoSectionError: root, nameSpaces = parseAndGetNameSpaces(EASchemaFile) # # If a default namespace is present, then don't process further. if "" in nameSpaces: return try: includeEntries = [x[1] for x in config.items('includes')] fixIncludes(root, includeEntries, nameSpaces) except cp.NoSectionError: pass try: ignoreElementNames = config.get('allowedGMLAbstractFeatures', 'names') except cp.NoSectionError: ignoreElementNames = [] # # Important dictionary for traversing the EA schema document parentChildMap = dict((c, p) for p in root.getiterator() for c in p) # # With instance or object diagrams in the Model, lots of cruft is generated as # well. Perhaps there's a way to turn this off in EA. The rest of the 'fix' routines # are cleaning up residual issues. cleanUpTree(root, nameSpaces, parentChildMap, ignoreElementNames) # # Fix elements' types as needed/configured try: dataTypesDic = dict( [tuple(x[1].split()) for x in config.items('dataTypes')]) changeElements(root, nameSpaces, dataTypesDic, 'type') except cp.NoSectionError: pass # # Fix elements that refer to code lists try: codeListsDic = dict(config.items('codeLists')) fixCodeLists(root, nameSpaces, codeListsDic) except cp.NoSectionError: pass # # Fix substitution groups try: subGroupsDic = dict(config.items('substitutionGroups')) changeElements(root, nameSpaces, subGroupsDic, 'substitutionGroup') except cp.NoSectionError: pass # # Fix objects that inherit/extend existing GML types try: baseExtensionsDic = dict(config.items('baseExtensions')) fixBaseExtensions(root, baseExtensionsDic, nameSpaces) except cp.NoSectionError: pass # # Bug in EA: Does not insert nillable attribute when nillable='true' in EA UML model. try: nilledElements = config.get('setNilAttribute', 'names').split(',') setNilElements(root, nilledElements, nameSpaces) except cp.NoSectionError: pass # # Bug in EA: Attributes' documentation strings are not inserted into schema. try: attributeDocStringsDic = dict(config.items('attributeDocStrings')) setCommentsForAttributes(root, attributeDocStringsDic, nameSpaces) except cp.NoSectionError: pass # # One-off for issues than cannot be represented in the UML->XML realization try: adjustmentDic = [ dict(config.items('adjustment%d' % num)) for num in range(int(config.get('adjustments', 'number'))) ] applyAdjustments(root, adjustmentDic, nameSpaces) except cp.NoSectionError: pass # # One-off python code instructions for UML->XML realization try: for cmd in [ config.get('addendum%d' % num, 'code') for num in range(int(config.get('addendums', 'number'))) ]: exec(cmd) except cp.NoSectionError: pass # # For some reason EA does not implement tag "attributeFormDefault" as a attribute # to the root element, need to add it here. # if root.get('attributeFormDefault') == None: root.set('attributeFormDefault', 'unqualified') # # Write out the modified EA schema doc = ET.ElementTree(root) doc.write(outputfile, xml_declaration=True, encoding="UTF-8", method="xml") del doc # # EA does not output the default namespace at the moment. Will set it here. ET.register_namespace("", DefaultNamespace) # # Rewrite to set default namespace root, nameSpaces = parseAndGetNameSpaces(outputfile) doc = ET.ElementTree(root) doc.write(outputfile, xml_declaration=True, encoding="UTF-8", method="xml") del doc # # Now prettify the schema file xmltext = open(outputfile, 'r').read() xmlpp.pprint(xmltext.replace('" />', '"/>'), open(outputfile, 'w'), indent=4) xmltext = open(outputfile, 'r').read() # # From stackoverflow 'nbolton' textnode_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL) prettyXml = textnode_re.sub('>\g<1></', xmltext) open(outputfile, 'w').write(prettyXml)
import xmlpp TAB = 8 def openFile (fileName , mode) : try : fich = open(fileName , mode) return fich except : sys.stderr.write("Error open file " + fileName + " mode : " + mode.upper()) raise SystemExit filename = "coches.xml" fileR = openFile(filename , "r") dataFile = fileR.read() fileR.close() fileW = openFile("/tmp/a" , "w") xmlpp.pprint(dataFile , fileW , TAB , 80) fileW.close() fileW = openFile("/tmp/a" , "r") print "!" , dataFile print "!" , fileW.read() fileW.close() shutil.move("/tmp/a" , filename)
node2.setAttribute("id", 'ATTACHED_TUNER_' + tuner_name_var + '_FULLNAME') node2.setAttribute("label", '9020') node2.setAttribute("type", 'bool') node2.setAttribute("default", 'false') node_cat.appendChild(node2) node3 = xmldoc.createElement("setting") node3.setAttribute("id", 'ATTACHED_TUNER_' + tuner_name_var + '_DISABLE') node3.setAttribute("label", '9030') node3.setAttribute("type", 'bool') node3.setAttribute("default", 'false') node_cat.appendChild(node3) # for tuner break ###################################################################################################### # save file back try: outputfile=open(__settings_xml__, 'w') xmlpp.pprint(xmldoc.toxml(), output=outputfile, indent=2) outputfile.close() except IOError: print 'Error writing file ', __settings_xml__ ###################################################################################################### # dialog is closed already so just open settings again xbmcaddon.Addon(id='driver.dvb.hdhomerun').openSettings()
node2.setAttribute("type", 'labelenum') node2.setAttribute("default", 'auto') node2.setAttribute("values", 'auto|RC5|NEC|RC6') node_cat.appendChild(node2) node3 = xmldoc.createElement("setting") node3.setAttribute( "id", 'ATTACHED_TUNER_' + tuner_serial + '_KEYMAP') node3.setAttribute("label", '9030') node3.setAttribute("type", 'text') node3.setAttribute("default", 'rc_key_ok') node_cat.appendChild(node3) # for tuner break ###################################################################################################### # save file back try: outputfile = open(__settings_xml__, 'w') xmlpp.pprint(xmldoc.toxml(), output=outputfile, indent=2) outputfile.close() except IOError: print 'Error writing file ', __settings_xml__ ###################################################################################################### # dialog is closed already so just open settings again xbmcaddon.Addon(id='driver.dvb.sundtek-mediatv').openSettings()
def save(xmlDoc, path): encoding = "Windows-1252" xmlData = xmlDoc.toprettyxml(indent=" ") xmlData = xmlData.replace('<?xml version="1.0" ?>', '<?xml version="1.0" encoding="utf-16"?>') xmlFile = open(path, "w", encoding=encoding) xmlpp.pprint(xmlData, xmlFile, indent=2)