def transform(fin, fout, options): ''' Read svg from file object fin, write output to file object fout options.png (boolean) Try to produce PNG output options.font (string) Font family to use (Ubuntu: Purisa) ''' etree.register_namespace('', 'http://www.w3.org/2000/svg') root = etree.parse(fin).getroot() w, h = root.attrib.get('width', ''), root.attrib.get('height', '') if w.endswith('in') or h.endswith('in'): global gCoordinates gCoordinates = 'in' _transform(root, options) scruffySvg = etree.tostring(root) + '\n' if options.png: import subprocess png = subprocess.Popen(['rsvg-convert', '-f', 'png'], stdin=subprocess.PIPE, stdout=subprocess.PIPE).communicate(input=scruffySvg)[0] fout.write(png) else: fout.write(scruffySvg)
def limit_rdb(services_rdb, full_factory_map, full_constructor_map): ET.register_namespace('','http://openoffice.org/2010/uno-components') tree = ET.parse(services_rdb[0]) root = tree.getroot() for component in root.findall('{http://openoffice.org/2010/uno-components}component'): # direct uri = component.get('uri') component_name = None if uri != None: component_name = re.sub('^vnd.sun.star.expand:\$LO_LIB_DIR/([^.]*).so$', '\\1.a', uri) if component_name in full_factory_map: continue # via a constructor - limit only to those we have has_constructor = False for implementation in component.findall('{http://openoffice.org/2010/uno-components}implementation'): constructor = implementation.get('constructor') if constructor in full_constructor_map: has_constructor = True else: component.remove(implementation) if not has_constructor: root.remove(component) tree.write(services_rdb[0] + '.out', xml_declaration = True, method = 'xml')
def to_string(self, endpoints): """ Converts the given endpoint description beans into a string :param endpoints: A list of EndpointDescription beans :return: A string containing an XML document """ # Make the ElementTree root = self._make_xml(endpoints) tree = ElementTree.ElementTree(root) # Force the default name space ElementTree.register_namespace("", EDEF_NAMESPACE) # Make the XML for encoding in ('unicode', 'UTF-8'): # Prepare a StringIO output output = StringIO() try: # Try to write with a correct encoding tree.write(output, encoding=encoding, xml_declaration=True, method="xml") break except LookupError: # 'unicode' is needed in Python 3, but unknown in Python 2... continue else: raise LookupError("Couldn't find a valid encoding") return output.getvalue()
def printDistAndPace(self, inputFile, prefix=_defaultPrefix): ET.register_namespace('', 'http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2') ET.register_namespace('TPX', "http://www.garmin.com/xmlschemas/UserProfile/v2") tree = ET.parse(inputFile) root = tree.getroot() points = [] for lap in root.iter(prefix + "Trackpoint"): posTag = lap.find(prefix + "Position") if posTag is None: continue lat = posTag.find(prefix + "LatitudeDegrees").text lon = posTag.find(prefix + "LongitudeDegrees").text time = lap.find(prefix + "Time").text timeObj = datetime.strptime(time, _dateFormat) points.append( ((lat, lon), timeObj) ) td = points[-1][1] - points[0][1] totalMiles = self.getMiles(points) self.printOutput(td.seconds, totalMiles)
def fix_graphml_format_better(cls, name, gridfs): cls._logger.info("Reformatting file to fix GDO graphml formatting using element tree") replacements = {} with gridfs.get_last_version(name) as f: tree = ElementTree.parse(f) f_id = f._id for key_entry in tree.findall("{http://graphml.graphdrawing.org/xmlns}key"): key_name = key_entry.attrib['attr.name'] id = key_entry.attrib['id'] key_entry.attrib['id'] = key_name replacements[id] = key_name # cls._logger.info("Name: %s, Key %s", key_name, key_entry) # cls._logger.info("Dict %s", replacements) root=tree.getroot() for data_entry in root.iter("{http://graphml.graphdrawing.org/xmlns}data"): found_key = data_entry.attrib['key'] data_entry.set('key', replacements[found_key]) ElementTree.register_namespace('', "http://graphml.graphdrawing.org/xmlns") with gridfs.new_file(filename=name, content_type="text/xml") as des: tree.write(des, encoding='utf-8', method='xml') cls._logger.info("Deleting old version of file %s", f_id) gridfs.delete(f_id)
def auth_success_response(user, pgt, proxies): etree.register_namespace('cas', CAS_URI) response = etree.Element(CAS + 'serviceResponse') auth_success = etree.SubElement(response, CAS + 'authenticationSuccess') username = etree.SubElement(auth_success, CAS + 'user') username.text = user.username attrs = {} for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user): if custom: attrs.update(custom) identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user) for i in rr] if identifiers: # Singular `identifier`, as that is the name of the element tag(s). attrs['identifier'] = identifiers if attrs: formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER) formatter(auth_success, attrs) if pgt: pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket') pgtElement.text = pgt if proxies: proxiesElement = etree.SubElement(auth_success, CAS + "proxies") for proxy in proxies: proxyElement = etree.SubElement(proxiesElement, CAS + "proxy") proxyElement.text = proxy return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')
def save_element(elem, path): if elem is None: return if not path or path is None: return parent = os.path.dirname(path) if not os.path.isdir(parent): os.makedirs(parent, mode=0o755, exist_ok=True) os.chmod(parent, 0o0755) try: # Get the elements default namespace namespace = getNamespace(elem) # Pretty up the element indent(elem) # Register the discovered namespace as the default ET.register_namespace("", namespace) # Create a new ElementTree with this element as the root elem_tree = ET.ElementTree(element=elem) # Write the full tree to a file elem_tree.write(path, xml_declaration=False, encoding="UTF-8", method="xml") os.chmod(path, 0o0664) return True except: print(" *** Error writing new element to path %s" % path) print(" Exception Type: ", sys.exc_info()[0]) print(" Exception Value: ", sys.exc_info()[1]) return False
def __init__(self, graph=None, encoding='utf-8', prettyprint=True, version='1.2draft'): try: import xml.etree.ElementTree as ET except ImportError: raise ImportError('GEXF writer requires ' 'xml.elementtree.ElementTree') self.prettyprint = prettyprint self.encoding = encoding self.set_version(version) self.xml = Element('gexf', {'xmlns': self.NS_GEXF, 'xmlns:xsi': self.NS_XSI, 'xsi:schemaLocation': self.SCHEMALOCATION, 'version': self.VERSION}) ET.register_namespace('viz', self.NS_VIZ) # counters for edge and attribute identifiers self.edge_id = itertools.count() self.attr_id = itertools.count() self.all_edge_ids = set() # default attributes are stored in dictionaries self.attr = {} self.attr['node'] = {} self.attr['edge'] = {} self.attr['node']['dynamic'] = {} self.attr['node']['static'] = {} self.attr['edge']['dynamic'] = {} self.attr['edge']['static'] = {} if graph is not None: self.add_graph(graph)
def remove_office_metadata(file_name): """ Remove all metadata from Microsoft Office 2007+ file types such as docx, pptx, and xlsx. :param str file_name: The path to the file whose metadata is to be removed. """ ns = { 'cp': 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties', 'dc': 'http://purl.org/dc/elements/1.1/', 'dcterms': 'http://purl.org/dc/terms/', 'dcmitype': 'http://purl.org/dc/dcmitype/', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance' } for prefix, uri in ns.items(): ElementTree.register_namespace(prefix, uri) _, file_ext = os.path.splitext(file_name) tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name), suffix=file_ext) os.close(tmpfd) with zipfile.ZipFile(file_name, 'r') as zin: with zipfile.ZipFile(tmpname, 'w') as zout: zout.comment = zin.comment for item in zin.infolist(): data = zin.read(item.filename) if item.filename == 'docProps/core.xml': root = ElementTree.fromstring(data) root.clear() data = ElementTree.tostring(root, 'UTF-8') zout.writestr(item, data) os.remove(file_name) os.rename(tmpname, file_name)
def transform(fin, fout, options): ''' Read svg from file object fin, write output to file object fout options.png (boolean) Try to produce PNG output options.font (string) Font family to use (Ubuntu: Purisa) ''' pp = re.compile('<polygon fill="([^"]+)" stroke="none" points="([^"]+)"/>') for p in pp.findall(fin): if fin.find('<polygon fill="none" stroke="black" points="'+p[1]+'"/>') > 0: fin = fin.replace('<polygon fill="none" stroke="black" points="'+p[1]+'"/>','<polygon fill="'+p[0]+'" stroke="black" points="'+p[1]+'"/>') fin = fin.replace('<polygon fill="'+p[0]+'" stroke="none" points="'+p[1]+'"/>','') etree.register_namespace('', 'http://www.w3.org/2000/svg') root = etree.parse(StringIO.StringIO(fin)).getroot() w, h = root.attrib.get('width', ''), root.attrib.get('height', '') if w.endswith('in') or h.endswith('in'): global gCoordinates gCoordinates = 'in' _transform(root, options) scruffySvg = etree.tostring(root) + '\n' if options['png']: import subprocess png = subprocess.Popen(['rsvg-convert', '-f', 'png', '-d', '180', '-p', '180'], stdin=subprocess.PIPE, stdout=subprocess.PIPE).communicate(input=scruffySvg)[0] fout.write(png) else: fout.write(scruffySvg)
def __init__(self, chapter): """ :param chapter: the chapter object :type chapter: :py:class:`Chapter` :return: """ # First, parse the package file to get to the content ET.register_namespace('', "http://www.idpf.org/2007/opf") root = ET.parse(os.path.join(chapter.source, "package.opf")).getroot() # First get the simple metadata self._title = root.find(".//{http://purl.org/dc/elements/1.1/}title").text dt = root.find(".//{http://www.idpf.org/2007/opf}meta[@property='dcterms:date']").text # TODO: the format string should be imported from the rp2epub package! self._date = datetime.strptime(dt, "%Y-%m-%dT%M:%S:00Z") self._authors = [] self._editors = [] for creator in root.findall(".//{http://purl.org/dc/elements/1.1/}creator"): if creator.get("role", default="editor") == "author": self._authors.append(creator.text) else: self._editors.append(creator.text) # Get the manifest entries self._manifest = self._get_manifest(chapter.target, root) # Get the spine self._spine = self._get_spine(chapter.target, root)
def getAppIconName(decompileDir): """ 从AndroidManifest.xml中获取游戏图标的名称 """ manifestFile = decompileDir + "/AndroidManifest.xml" manifestFile = file_utils.getFullPath(manifestFile) ET.register_namespace('android', androidNS) tree = ET.parse(manifestFile) root = tree.getroot() applicationNode = root.find('application') if applicationNode is None: return "ic_launcher" key = '{'+androidNS+'}icon' iconName = applicationNode.get(key) if iconName is None: return "ic_launcher" name = iconName[10:] return name
def appendSplashActivity(decompileDir, splashType): manifestFile = decompileDir + "/AndroidManifest.xml" manifestFile = file_utils.getFullPath(manifestFile) ET.register_namespace('android', androidNS) key = '{' + androidNS + '}name' screenkey = '{' + androidNS + '}screenOrientation' theme = '{' + androidNS + '}theme' tree = ET.parse(manifestFile) root = tree.getroot() applicationNode = root.find('application') if applicationNode is None: return splashNode = SubElement(applicationNode, 'activity') splashNode.set(key, 'com.u8.sdk.SplashActivity') splashNode.set(theme, '@android:style/Theme.Black.NoTitleBar.Fullscreen') if splashType[:1] == '1': splashNode.set(screenkey, 'landscape') else: splashNode.set(screenkey, 'portrait') intentNode = SubElement(splashNode, 'intent-filter') actionNode = SubElement(intentNode, 'action') actionNode.set(key, 'android.intent.action.MAIN') categoryNode = SubElement(intentNode, 'category') categoryNode.set(key, 'android.intent.category.LAUNCHER') tree.write(manifestFile, 'UTF-8')
def __init__(self): tree = ET.parse("Tokens.xml") root = tree.getroot() ET.register_namespace("","http://merthsoft.com/Tokens") self.tokens = {} # Empty list to be filled by tokens # Tokens composed of two bytes (eg. accents, lowercase letters) self.two_byte_tokens = {} # dbtokens = double byte tokens - The first byte of each double # byte token. Used internally for checking whether or not a byte # is a double byte. self.__dbtokens = (0x5C, 0x5D, 0x5E, 0x60, 0x61, 0x62, 0x63, 0x7E, 0xAA, 0xBB, 0xEF) for token in root.findall("{http://merthsoft.com/Tokens}Token"): string = token.get("string") byte = int(token.get("byte").replace("$", "0x"),16) # If the byte doesn't have a string attatched to it in the # XML file, it's a double byte. if not string: for child in token.findall( "{http://merthsoft.com/Tokens}Token"): sub_string = child.get("string") # Convert string of byte into integer by removing # Tokens.xml's formatting sub_byte = int(child.get("byte").replace("$", "0x"),16) self.two_byte_tokens[byte,sub_byte] = sub_string else: self.tokens[byte] = string
def build_DAR(urls): """ urls consist of a list of tuples (dl_dir, url), where dl_dir is the download directory for each url""" if use_register: try: ET.register_namespace("ngeo", NGEO_URI) ET.register_namespace("xsi", XSI_URI) except Exception: pass root = ET.Element(NGEO_NS+DA_RESP, {XSI_NS+"schemaLocation":SCHEMA_LOCATION}) ET.SubElement(root, NGEO_NS+MONITORINGSTATUS).text = "IN_PROGRESS" pa_list = ET.SubElement(root, NGEO_NS+PRODACCESSLIST) for url in urls: pa = ET.SubElement(pa_list, NGEO_NS+PRODACCESS) ET.SubElement(pa, NGEO_NS+PRODACCESSURL).text = url[1] ET.SubElement(pa, NGEO_NS+PRODACCESSSTATUS).text = "READY" ET.SubElement(pa, NGEO_NS+PRODDOWNLOADDIRECTORY).text = url[0] if LOCAL_DEBUG > 0: print "dAR:\n"+ DAR_PREAMBLE + ET.tostring(root) return DAR_PREAMBLE + ET.tostring(root)
def createTMGFromRelease(args): """ Create a local TrackingMaterialGroup file starting from a tracking material reco XML file in release. This is useful for the very first time the users want to test a geoemetry for which no such file has ever been created in this package. """ tracker_reco_material = checkFileInRelease(args.createTMG) if not tracker_reco_material: print "Input file not found in release, quitting" sys.exit(1) ET.register_namespace('', "http://www.cern.ch/cms/DDL") tree = ET.parse(tracker_reco_material) root = tree.getroot() sections = root.getchildren() for spec_par in root.iter('%sSpecPar' % TAG_PREFIX): spec_par.attrib.pop('eval', None) # Cannot remove elements in place: store them all here and remove them later on. to_be_removed = [] for parameter in spec_par.iter('%sParameter' % TAG_PREFIX): to_be_removed.append(parameter) el = ET.Element("Parameter") el.set('name', 'TrackingMaterialGroup') el.set('value', spec_par.attrib['name']) spec_par.append(el) for d in to_be_removed: spec_par.remove(d) tree.write('trackingMaterialGroupFromRelease.xml', encoding='UTF-8', xml_declaration=True)
def processDir(sourceDir, targetDir, language="en"): ET.register_namespace('', 'http://www.loc.gov/standards/alto/ns-v2#') for subdir, dirs, files in os.walk(sourceDir): for file in files: fname = os.path.join(subdir, file) outputfname = os.path.join( targetDir, os.path.relpath(fname, sourceDir)) if not os.path.exists(os.path.dirname(outputfname)): os.makedirs(os.path.dirname(outputfname)) print fname print outputfname tree = ET.parse(fname) entities = dict() for t in tree.getroot().iter(tag="{http://www.loc.gov/standards/alto/ns-v2#}NamedEntityTag"): if entities.get(t.attrib.get('LABEL')) is None: entities[t.attrib.get('LABEL')] = [] entities.get(t.attrib.get('LABEL')).append(t) result = disambiguation.disambiguateList(entities.keys()) for key in result.keys(): if result.get(key) is not None and result.get(key)[0] is not None: for tag in entities[key]: tag.set("URI", result[key][0][1:-1]) tree.write( outputfname, xml_declaration=True, encoding='utf-8', method='xml')
def createWorkflow( self, experimentID,projectID, pipeline,status): """Create a Workflow Entry and return the primary key of the inserted workflow""" WorkflowStrXML = '<wrk:Workflow data_type="xnat:mrSessionData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wrk="http://nrg.wustl.edu/workflow" />' WorkflowDataElement = ET.fromstring(WorkflowStrXML) ET.register_namespace('wrk', 'http://nrg.wustl.edu/workflow') WorkflowDataElement.set('ID',experimentID) WorkflowDataElement.set('ExternalID',projectID) WorkflowDataElement.set('status',status) WorkflowDataElement.set('pipeline_name',pipeline) timeNow=time.localtime() xmlTime=time.strftime('%Y-%m-%dT%H:%M:%S', timeNow) prettyTimeNow=time.strftime('%Y-%m-%dT%H-%M-%S', timeNow) WorkflowDataElement.set('launch_time',xmlTime) WorkflowDataStr = ET.tostring(WorkflowDataElement) if sys.platform != 'win32': WorkflowWriteStr = '/tmp/Workflow_%s_%s.xml' % (experimentID,prettyTimeNow) with open(WorkflowWriteStr, 'wb') as outputFileObj: outputFileObj.write(WorkflowDataStr) #WorkflowSubmitStr = 'source $SCRIPTS_HOME/xnat-tools_setup.sh; $NRG_PACKAGES/tools/xnat-tools/StoreXML -u %s -p %s -host %s -location %s -allowDataDeletion true' % (self.User, self.Password, self.Server, WorkflowWriteStr) WorkflowSubmitStr = '$PIPELINE_HOME/xnat-tools/XNATRestClient -m PUT -user_session %s -host %s -remote "REST/workflows?req_format=xml" -local %s' % (self.JSESSION, self.Server, WorkflowWriteStr) subprocess.call(WorkflowSubmitStr, shell=True, stdout = open("/dev/null", "w")) workflowID = self.getQueuedWorkflowIdAsParameter(pipeline,experimentID) return workflowID else: ET.dump(WorkflowDataElement) return -1
def remap_output(csproj_path): # ElementTree.register_namespace('xmlns', 'http://schemas.microsoft.com/developer/msbuild/2003') tree = ElementTree.parse(csproj_path) root = tree.getroot() namespace = {'ns':'{http://schemas.microsoft.com/developer/msbuild/2003}'} property_groups_els = [elements for elements in root.findall('%(ns)sPropertyGroup'%namespace) if not elements.find('%(ns)sOutputPath' % namespace) == None] for property_group_els in property_groups_els: isdebug = 'Debug' in property_group_els.get('Condition') output_path_els = property_group_els.find('%(ns)sOutputPath' % namespace) source_path = output_path_els.text target_path = find_relpath(csproj_path, 'ThinkGeo', isdebug); output_path_els.text = target_path projectrefs_els = [elements for elements in root.findall('%(ns)sItemGroup/%(ns)sProjectReference'%namespace)] for projectref_els in projectrefs_els: private_element = projectref_els.find('%(ns)sPrivate'%namespace) if private_element == None: private_element = ElementTree.Element('%(ns)sPrivate'%namespace) projectref_els.append(private_element) private_element.text = str(False) ElementTree.register_namespace('', 'http://schemas.microsoft.com/developer/msbuild/2003') tree.write(csproj_path, xml_declaration=True, encoding='utf-8') print('Remap', path.basename(csproj_path), 'completed.')
def merge_androidmanifest_xml(): try: from xml.etree import ElementTree as ET ET.register_namespace('android', xmlns_android); #extra项目 print extra_file_path+"/AndroidManifest.xml" extra_parse = ET.parse(extra_file_path+"/AndroidManifest.xml") extra_root = extra_parse.getroot() #target项目 target_parse = ET.parse(target_file_path+"/AndroidManifest.xml") target_root = target_parse.getroot() target_application = target_root.find("application") #合并两个项目的meta-data merge_hkc_meta(extra_root,target_root,target_application) #合并两个项目的activity merge_hkc_activity(extra_root,target_root,target_application) #合并两个项目的service merge_hkc_services(extra_root,target_root,target_application) target_parse.write(target_file_path+"/AndroidManifest.xml","utf-8",True) except Exception, e: print "merge_androidmanifest_xml "+str(e)
def redefine_app_name(): print "\n 新名字: hkc_app_name" try: from xml.etree import ElementTree as ET ET.register_namespace('android', xmlns_android); target_parse = ET.parse(target_file_path+"/AndroidManifest.xml") target_root = target_parse.getroot() target_application = target_root.find("application") orig_name = target_application.attrib[xmlns_android_attrib+"label"] print "orig_name:\t"+orig_name target_application.attrib[xmlns_android_attrib+"label"] = "@string/hkc_app_name" target_parse.write(target_file_path+"/AndroidManifest.xml","utf-8",True) target_strings_parse = ET.parse(target_file_path+"/res/values/strings.xml") target_string_root = target_strings_parse.getroot() strings_item = target_string_root.findall("string") for string_i in strings_item: if orig_name.find(string_i.attrib['name'])==8 : print string_i.text string_i.text = "@string/hkc_app_name" target_strings_parse.write(target_file_path+"/res/values/strings.xml","utf-8",True) except Exception, e: print "redefine_app_name "+str(e)
def generate_sketch_fontfile(data): print "Generate Sketch font file" ET.register_namespace('', "http://www.w3.org/2000/svg") ET.register_namespace('xlink', "http://www.w3.org/1999/xlink") svg_path = os.path.join(FONTS_FOLDER_PATH, 'ionicons.svg') sketch_path = os.path.join(FONTS_FOLDER_PATH, 'ionicons_sketch.svg') # with open(svg_path, 'r') as utf8_file: doc = ET.parse(svg_path) doc.write(sketch_path, xml_declaration=True, method='html') sketch_file = open(sketch_path, 'r+') sketch_text = sketch_file.read() sketch_file.seek(0) for ionicon in data['icons']: # uniF2CA code = string.atoi(ionicon['code'], 16) org = '&#%d;' % (code) hexvalue = '&#x%s' % (ionicon['code'].replace('0x', '').upper()) sketch_text = sketch_text.replace(org, hexvalue) sketch_file.write(sketch_text) sketch_file.close()
def setUp(self): self.expect = ["BEGIN:VCARD", "VERSION:3.0", "PRODID:-//Gramps//NONSGML Gramps %s//EN" % VERSION, "FN:Lastname", "N:Lastname;;;;", "SORT-STRING:" + "Lastname".ljust(55), "END:VCARD"] date = time.localtime(time.time()) self.input_list = ["BEGIN:VCARD", "VERSION:3.0", "FN:Lastname", "N:Lastname;;;;", "END:VCARD"] self.header = """<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE database PUBLIC "-//GRAMPS//DTD GRAMPS XML %s//EN" "http://gramps-project.org/xml/%s/grampsxml.dtd">""" % \ (GRAMPS_XML_VERSION, GRAMPS_XML_VERSION) strng = """<database xmlns="http://gramps-project.org/xml/%s/"> <header> <created date="%04d-%02d-%02d" version="%s"/> <researcher/> </header> <people> <person id="I0000" handle="_0000"> <name type="Birth Name"> <surname>Lastname</surname> </name> </person> </people> </database>""" % \ (GRAMPS_XML_VERSION, date[0], date[1], date[2], VERSION) namespace = "http://gramps-project.org/xml/%s/" % GRAMPS_XML_VERSION ET.register_namespace("", namespace) self.database = ET.XML(strng) self.people = self.database[1] self.person = self.people[0] self.name = self.person[0] self.lastname = self.name[0]
def SaveLayout(self,Form = None,Fields = None,Name = None): #find citation element for element in self.root: if Form in element.tag: form = element break for element in form: if 'layout' in element.tag: form = element break for element in form: form.remove(element) bns = (self.root.tag).find('{') ens = (self.root.tag).find('}') ns = self.root.tag[bns+1:ens] ET.register_namespace('',ns) for field in Fields: value = field if 'text' in value: field = ET.SubElement(form,value) else: field = ET.SubElement(form,'text ' + value) self.tree.write(Name)
def to_string(self, endpoints): # type: (List[EndpointDescription]) -> str """ Converts the given endpoint description beans into a string :param endpoints: A list of EndpointDescription beans :return: A string containing an XML document """ # Make the ElementTree root = self._make_xml(endpoints) tree = ElementTree.ElementTree(root) # Force the default name space ElementTree.register_namespace("", EDEF_NAMESPACE) # Make the XML # Prepare a StringIO output output = StringIO() # Try to write with a correct encoding tree.write( output, encoding=self._encoding, xml_declaration=self._xml_declaration, ) return output.getvalue().strip()
def __init__(self, pom): """ Load the specified pom.xml. :param pom: pom to load """ Xml.register_namespace('', 'http://maven.apache.org/POM/4.0.0') self.pom = Xml.parse(pom)
def craete_xbrl_url_json(since,p): #有報キャッチャーWebServiceのAtomAPIアドレス<http://resource.ufocatch.com/> base_url = 'http://resource.ufocatch.com/atom/' namespace = '{http://www.w3.org/2005/Atom}' #有報キャッチャーのページ page = 1 + p count = 0 while True: #文字列変換 t_symbol = str(page) print('page:'+t_symbol + ', loading...') #企業毎の有報へのデータへのリンク情報を取得 response_string = get_link_info_str(t_symbol, base_url) #xmlをparseするElementTreeを取得 ET_tree = ET.fromstring( response_string ) ET.register_namespace('',namespace[1:-1]) #downloadファイルの対象を取得 info_dict = get_link(ET_tree,namespace,since) count += len(info_dict) if len(info_dict) == 0 : #取得データがなくなり次第、処理終了 print('process' + str(p) + ':complete a download!! [' + str(count) + ']') break #Request用のJson形式のファイルを作成 json_directory=os.getcwd()+'/downloaded_info' make_directory(json_directory) ofname = json_directory+'/dat_download_'+t_symbol+'.json' write_download_info(ofname,info_dict) page += proc
def AddContentProtection(options, container, tracks): kids = [] for track in tracks: kid = track.kid if kid is None: PrintErrorAndExit('ERROR: no encryption info found in track '+str(track)) if kid not in kids: kids.append(kid) xml.register_namespace('mas', MARLIN_MAS_NAMESPACE) xml.register_namespace('mspr', PLAYREADY_MSPR_NAMESPACE) #xml.SubElement(container, 'ContentProtection', schemeIdUri='urn:mpeg:dash:mp4protection:2011', value='cenc') if options.marlin: cp = xml.SubElement(container, 'ContentProtection', schemeIdUri=MARLIN_SCHEME_ID_URI) cids = xml.SubElement(cp, '{' + MARLIN_MAS_NAMESPACE + '}MarlinContentIds') for kid in kids: cid = xml.SubElement(cids, '{' + MARLIN_MAS_NAMESPACE + '}MarlinContentId') cid.text = 'urn:marlin:kid:' + kid if options.playready_header: if options.encryption_key: kid = options.kid_hex key = options.key_hex else: kid = kids[0] key = None header_b64 = ComputePlayReadyHeader(options.playready_header, kid, key) cp = xml.SubElement(container, 'ContentProtection', schemeIdUri=PLAYREADY_SCHEME_ID_URI) pro = xml.SubElement(cp, '{' + PLAYREADY_MSPR_NAMESPACE + '}pro') pro.text = header_b64
def migrate(*args, **kwargs): """ Adds a "checksums" DictField and populates it with the known checksum type and value. Templatizes the XML in "repodata". :param args: unused :type args: list :param kwargs: unused :type kwargs: dict """ try: ET.register_namespace('rpm', RPM_NAMESPACE) except AttributeError: # python 2.6 doesn't have the register_namespace function ET._namespace_map[RPM_NAMESPACE] = 'rpm' db = connection.get_database() rpm_collection = db['units_rpm'] srpm_collection = db['units_srpm'] drpm_collection = db['units_drpm'] for rpm in rpm_collection.find({}, ['checksum', 'checksumtype', 'repodata']): migrate_rpm_base(rpm_collection, rpm) for srpm in srpm_collection.find({}, ['checksum', 'checksumtype', 'repodata']): migrate_rpm_base(srpm_collection, srpm) migrate_drpms(drpm_collection)
def main(): if (len(sys.argv) != 3 or not os.path.isfile(sys.argv[1]) or not os.path.isfile(sys.argv[2])): print "Usage: ", sys.argv[0], "project_file rtt_file" sys.exit(-1) pd = project_data.ProjectData(sys.argv[1]) # pd.dump() et.register_namespace("xi", "http://www.w3.org/2001/XInclude") rtt = et.ElementTree(file=sys.argv[2]) # et.dump(rtt.getroot()) rtt_pages = rtt.findall(".//page") rtt_pages_dict = {} for p in rtt_pages: rtt_pages_dict[p.attrib["id"]] = p for (pageid, status, timestamp) in pd.get_pages(): #look for pageid in rtt file l = pd.get_lines(pageid) p = rtt_pages_dict[pageid] i = p.find("image") le = i.find("lines") if le == None: le = et.SubElement(i, "lines") le.text = ",".join([str(X) for X in l[project_data.DATA]]) rtt.write(sys.stdout, encoding="utf-8", xml_declaration=True)
def modifyStartActivity(decompileDir, appid, packageName): manifestFile = decompileDir + "/AndroidManifest.xml" manifestFile = file_utils.getFullPath(manifestFile) ET.register_namespace('android', androidNS) key = '{' + androidNS + '}name' valKey = '{'+androidNS+'}value' tree = ET.parse(manifestFile) root = tree.getroot() applicationNode = root.find('application') if applicationNode is None: return metaNode = SubElement(applicationNode, 'meta-data') metaNode.set(key, 'lenovo:channel') metaNode.set(valKey, appid) activityNodeLst = applicationNode.findall('activity') if activityNodeLst is None: return activityName = '' for activityNode in activityNodeLst: bMain = False intentNodeLst = activityNode.findall('intent-filter') if intentNodeLst is None: break for intentNode in intentNodeLst: bFindAction = False bFindCategory = False actionNodeLst = intentNode.findall('action') if actionNodeLst is None: break for actionNode in actionNodeLst: if actionNode.attrib[key] == 'android.intent.action.MAIN': bFindAction = True break categoryNodeLst = intentNode.findall('category') if categoryNodeLst is None: break for categoryNode in categoryNodeLst: if categoryNode.attrib[key] == 'android.intent.category.LAUNCHER': bFindCategory = True break if bFindAction and bFindCategory: bMain = True intentNode.remove(actionNode) actionNode = SubElement(intentNode, 'action') actionNode.set(key, 'lenovoid.MAIN') intentNode.remove(categoryNode) categoryNode = SubElement(intentNode, 'category') categoryNode.set(key, 'android.intent.category.DEFAULT') break if bMain: activityName = activityNode.attrib[key] break for activityNode in activityNodeLst: name = activityNode.get(key) if name == 'com.lenovo.lsf.gamesdk.ui.WelcomeActivity': intentNode = SubElement(activityNode, 'intent-filter') actionNode = SubElement(intentNode, 'action') actionNode.set(key, 'android.intent.action.MAIN') categoryNode = SubElement(intentNode, 'category') categoryNode.set(key, 'android.intent.category.LAUNCHER') receiverNodeLst = applicationNode.findall('receiver') if receiverNodeLst != None: for receiverNode in receiverNodeLst: name = receiverNode.get(key) if name == 'com.lenovo.lsf.gamesdk.receiver.GameSdkReceiver': intentNodeLst = receiverNode.findall('intent-filter') for intentNode in intentNodeLst: actionNode = SubElement(intentNode, 'action') actionNode.set(key, appid) categoryNode = SubElement(intentNode, 'category') categoryNode.set(key, packageName) break elif name == 'com.lenovo.lsf.gamesdk.receiver.GameSdkAndroidLReceiver': intentNodeLst = receiverNode.findall('intent-filter') for intentNode in intentNodeLst: categoryNode = SubElement(intentNode, 'category') categoryNode.set(key, packageName) break providerNodeLst = applicationNode.findall('provider') if providerNodeLst != None: for providerNode in providerNodeLst: name = providerNode.get(key) if name == 'android.support.v4.content.FileProvider': providerNode.set('{'+androidNS+'}authorities',packageName+'.fileprovider') break tree.write(manifestFile, 'UTF-8') return activityName
description=Globals.proj_title + ". Add or remove property files containing include and library path information from a Visual Studio project", epilog="Created by " + Globals.proj_author + ", 2017. Contact at [email protected] for any issues or suggestions" ) parser.add_argument('filepath', default="", nargs='?', type=str, help="Filepath to the project file") parser.add_argument("-p, --prop-dir", default="", dest="prop_dir", nargs=1, help="Directory where the property files are located") parser.add_argument('--version', action='version', version="%(prog)s " + Globals.proj_version) args = parser.parse_args() #Register the namespace ET.register_namespace('', Globals.xmlns) #Create window and run! root = tk.Tk() app = PropertyManager(master=root, default_filepath=args.filepath, prop_dir=os.path.dirname(os.path.realpath(__file__)) if args.prop_dir == "" else args.prop_dir[0]) app.mainloop()
import xml.etree.ElementTree as ET with open('/apps/example.xml', 'r') as myfile: countrydata = myfile.read() ns = {'urn': 'urn:iso:std:iso:20022:tech:xsd:pacs.008.001.04'} ET.register_namespace('urn', 'urn:iso:std:iso:20022:tech:xsd:pacs.008.001.04') root = ET.fromstring(countrydata) # for fito in root.findall("urn:FIToFICstmrCdtTrf", ns): # print('----') # for header in fito.findall("urn:GrpHdr", ns): # name = header.find('urn:MsgId', ns) # print(header.text) headers = {} def transformItem(element): for item in element.getchildren(): if item.getchildren(): transformItem(item) else: tagName = item.tag.split('}')[1] headers[tagName] = item.text def eachItem(element): for item in element.getchildren(): tagName = item.tag.split('}')[1]
#!/usr/bin/python3 # -*- coding: utf-8 -*- import re import xml.etree.ElementTree as et et.register_namespace("mets", "http://www.loc.gov/METS/") et.register_namespace("mods", "http://www.loc.gov/mods/v3") et.register_namespace("tei", "http://www.tei-c.org/ns/1.0") et.register_namespace("dv", "http://www.dfg-viewer.de") et.register_namespace("xlink", "http://www.w3.org/1999/xlink") import urllib.request as ul class METSBuilder: def __init__(self, sign, title="-"): self.title = title self.sign = sign self.url = "http://diglib.hab.de/mss/" + sign + "/start.htm" self.struct = [] try: fileobject = ul.urlopen(self.url) except: print("Kein Digitalisat vorhanden unter " + self.url) else: try: facs = ul.urlopen("http://diglib.hab.de/mss/" + self.sign + "/facsimile.xml") except: print( "Keine facsimile.xml vorhanden unter http://diglib.hab.de/mss/" + self.sign + "/facsimile.xml")
import xml.etree.ElementTree as ET import sys ns = 'http://maven.apache.org/POM/4.0.0' ss = '-SNAPSHOT' # hack: register the namespace to avoid `.write` # from writing the `ns0` all over the place ET.register_namespace('', ns) tree = ET.parse('pom.xml') root = tree.getroot() version_node = root.find('{%s}version' % ns) assert version_node is not None, 'No <version> key' if version_node.text.endswith(ss): sys.exit() version_node.text = version_node.text + ss tree.write('pom.xml', xml_declaration = True, encoding = 'utf-8', method = 'xml') print 'Added %s to version' % ss
pubDate.text = formatdate() enclosure = ET.SubElement(new_item, "enclosure", attrib=attrib) parent_element.insert(4, new_item) if __name__ == "__main__": now = datetime.datetime.now() now_timestamp = formatdate() # rfc 2822 sparkle_file = sys.argv[1] title = sys.argv[2] url = sys.argv[3] os = sys.argv[4] length = sys.argv[5] ET.register_namespace( 'sparkle', 'http://www.andymatuschak.org/xml-namespaces/sparkle') namespace = { 'sparkle': 'http://www.andymatuschak.org/xml-namespaces/sparkle' } tree = ET.parse(sparkle_file) channel = tree.find("channel") attrib = { 'url': url, 'sparkle:version': now.strftime("%Y%m%d"), 'sparkle:shortVersionString': "nightly-" + now.strftime("%Y%m%d"), 'sparkle:os': os, 'length': length, 'type': "application/octet-stream" } # remove all publications of the same day (but not same os)
}, "http://diyhistory.org/public/phr2/ns/saji/witness": { "label": "Omeka:witness", "term": "saji:witness" } } for i in range(len(files)): file = files[i] print(str(i + 1) + "/" + str(len(files)) + "\t" + file) prefix = ".//{http://www.tei-c.org/ns/1.0}" tree = ET.parse(file) ET.register_namespace('', "http://www.tei-c.org/ns/1.0") root = tree.getroot() surfaceGrp = root.find(prefix + "surfaceGrp") manifest = surfaceGrp.get("facs") mani_data, label = get_mani_data(manifest) surfaces = root.findall(prefix + "surface") body = root.find(prefix + "body") # 第一階層 div1s = body.findall(prefix + "div1") members = []
def compute_stat(a_basedata_dir, a_dir1, a_dir2, \ a_ptrn = "", a_cmp = BINARY_OVERLAP, a_mark_difference = False): """ Compare markables in two annotation directories. @param a_basedata_dir - directory containing basedata for MMAX project @param a_dir1 - directory containing markables for the first annotator @param a_dir2 - directory containing markables for the second annotator @param a_ptrn - shell pattern for markable files @param a_cmp - mode for comparing two annotation spans @param a_mark_difference - boolean flag indicating whether detected differences should be added as separate markables to annotation files @return void """ global statistics # find annotation files from first directory if a_ptrn: dir1_iterator = glob.iglob(a_dir1 + os.sep + a_ptrn) else: dir1_iterator = os.listdir(a_dir1) # iterate over files from the first directory f1 = f2 = "" basename1 = markname = "" basedata_fname = base_key = "" fd1 = fd2 = basedata_fd = None t1 = t2 = t2_root = None f1_out = f2_out = "" annotations = None n = 0 # total number of words in a file for f1 in dir1_iterator: # get name of second file basename1 = os.path.basename(f1) print >> sys.stderr, "Processing file '{:s}'".format(f1) f2 = a_dir2 + os.sep + basename1 # open both files for reading fd1 = open(a_dir1 + os.sep + basename1, 'r') try: t1 = _ET.parse(fd1) except (IOError, _ET.ParseError): t1 = None finally: fd1.close() # read XML information from second file ignoring non-existent, empty, # and wrong formatted files try: fd2 = open(f2, 'r') try: t2 = _ET.parse(fd2) finally: fd2.close() except (IOError, _ET.ParseError): t2 = None if t1 is None or t2 is None: continue # determine the name of the markable for which we should calculate # annotations mname = MRKBL_NAME_RE.match(basename1).group(1).lower() # prepare containers for storing information about matching and # mismatching annotations # the 0-th element in the list is the number of matching annotations, # the 1-st element is the total number of tokens annotated with that # markables, the 2-nd element is a list of annotation span tuples which # are different in another annotation anno1 = [0, 0, []] anno2 = [0, 0, []] base_key = MARK_SFX_RE.sub("", basename1) if base_key in statistics: annotations = statistics[base_key]["annotators"] annotations[0][mname] = anno1 annotations[1][mname] = anno2 else: # obtain number of words from basedata file basedata_fname = a_basedata_dir + os.sep + base_key + BASEDATA_SFX basedata_fd = open(basedata_fname, "r") # get total number of words in a file n = len(_ET.parse(basedata_fd).findall("word")) basedata_fd.close() statistics[base_key] = { "tokens": n, "annotators": [{ mname: anno1 }, { mname: anno2 }] } # compare two XML trees _update_stat(t1, t2, anno1, anno2, a_cmp, a_mark_difference) # if we were asked to edit annotation files, write differences to new files if a_mark_difference: f1_out = _make_diff_name(f1) f2_out = _make_diff_name(f2) _ET.register_namespace('', NAMESPACE_PRFX + mname) mname = MRKBL_NAME_RE.match(f1_out).group(1).lower() # write difference for the first tree write_diff(f1_out, t1, anno2[-1], anno1[-1], mmax_level=mname) # for the second tree, if source tree with annotations is present, # modify it if t2: mname = MRKBL_NAME_RE.match(f2_out).group(1).lower() write_diff(f2_out, t2, anno1[-1], anno2[-1], mmax_level=mname) # otherwise, write a copy of t1 to the second file and set # the value of `diff_type' attribute to `MISSING' else: # create a copy of the first tree t2 = copy(t1) t2_root = t2.getroot() # add MISSING attribute to all XML for mark in t2_root: mark.attrib["diff_type"] = MISSING # dump modified XML tree to the second file t2.write(f2_out, encoding="UTF-8", xml_declaration=True) # remove markable tuples with different annotations to save memory del anno1[DIFF_MRKBL_IDX][:] del anno2[DIFF_MRKBL_IDX][:]
def register_namespaces(self, namespaces, default_ns=None): for prefix, uri in namespaces.items(): if prefix == default_ns: prefix = "" ET.register_namespace(prefix, uri)
# # We would appreciate acknowledgement if the software is used. import logging import os import xml.etree.ElementTree as ET _logger = logging.getLogger(os.path.basename(__file__)) logging.basicConfig(level=logging.DEBUG) import Objects XMLNS_TEST_CLAMSCAN = "file:///opt/local/bin/clamscan" XMLNS_TEST_UNREGGED = "file:///dev/random" ET.register_namespace("clam", XMLNS_TEST_CLAMSCAN) vo = Objects.VolumeObject() #Try and fail to add a non-Element to the list. failed = None _logger.debug("Before: " + repr(vo.externals)) try: vo.externals.append(1) failed = False except TypeError: failed = True except: failed = True raise _logger.debug("After: " + repr(vo.externals))
def _parse_cxl_file(self): ET.register_namespace('cxl', "http://cmap.ihmc.us/xml/cmap/") return ET.parse(self.cxl_file)
# to the filename of you choosing # $ python3 events.xml > events_modified.xml # # NOTE: This was tested with python3 on linux. Mileage may vary on other platforms. # read the filename from the first argument xmlfile = sys.argv[1] # this could also be done by hardcoding the filename below #xmlfile = "/home/rew/Events_ECI TCP-IP 55513.xml" # register the file's name space so it is not included in the output file. However # this could vary on future files, so it might need to be modified. This came from # the second line the input xml file: # <eventTrack ="http://www.egi.com/event_mff" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ET.register_namespace('', "http://www.egi.com/event_mff") # parse the xml file tree = ET.parse(xmlfile) # get the first element root = tree.getroot() # set the schema tag. This is based on the second line of the input file: # <eventTrack ="http://www.egi.com/event_mff" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> root.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") # iterate through all events in the file for event in root.findall('{http://www.egi.com/event_mff}event'): # find the event code
logger = logging.getLogger(__name__) nsmap = { 'atom' : 'http://www.w3.org/2005/Atom', 'gd' : 'http://schemas.google.com/g/2005', 'georss' : 'http://www.georss.org/georss', 'gml' : 'http://www.opengis.net/gml', 'gphoto' : 'http://schemas.google.com/photos/2007', 'media' : 'http://search.yahoo.com/mrss/', } for prefix, uri in nsmap.items(): if prefix == 'atom': prefix = '' ET.register_namespace(prefix, uri) # general node, can be any kind of element class PicasaNode(object): _elements = { # name namespace repeat node 'access' : ('gphoto', False, False), 'category' : ('atom', False, False), 'group' : ('media', False, True), 'id' : ('gphoto', False, False), 'keywords' : ('media', False, False), 'location' : ('gphoto', False, False), 'numphotos' : ('gphoto', False, False), 'Point' : ('gml', False, True), 'pos' : ('gml', False, False),
m = int(s / 60) s = s - m * 60 return 'PT{0:1g}H{1:1g}M{2:1g}S'.format(h, m, s) def _to_stream(template, RepresentationID, Number=0): template = template.replace("$RepresentationID$", "{0}") template = re.sub("\$Number\%([0-9]*)d\$", r"{1:\1d}", template) return template.format(RepresentationID, Number) def _ns(tag): return "{urn:mpeg:dash:schema:mpd:2011}" + tag ET.register_namespace('', 'urn:mpeg:dash:schema:mpd:2011') _ad_template = ET.fromstring("""<?xml version="1.0" encoding="utf-8"?> <MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:mpeg:dash:schema:mpd:2011" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd" profiles="urn:mpeg:dash:profile:isoff-live:2011" type="static" mediaPresentationDuration="PT5S" minBufferTime="PT16.6S"> <ProgramInformation> </ProgramInformation> <Period id="0" start="PT0.0S"> <AdaptationSet id="0" contentType="video" segmentAlignment="true" bitstreamSwitching="true" lang="und"> <Representation id="0" mimeType="video/mp4" codecs="avc1.640028" bandwidth="2027988" width="1920" height="1080" frameRate="30000/1001"> <SegmentTemplate timescale="1000000" duration="5000000" initialization="init-stream0.m4s" media="chunk-stream0-$Number%05d$.m4s" startNumber="1">
class Ods(Document.Document): """Open Document Spreadsheet fileformat""" inputfile = '' outputfile = '' work_dir = '' bait = '' can_work = False def __init__(self, input, output, work, bait): self.inputfile = input self.outputfile = output self.work_dir = work self.bait = bait self.can_work = False def inject_bait(self): found_it = False ##use always when search for something graph_style_name = 'ax99' draw_id = 'idx9' cell_used_style = 'ce1' ##seems not necessery row_used_style = 'ro1' ##seems not necessery picture_name = 'PictureXX' last_table = '' ###-----------------modifying the STYLE.XML file-----------------------------### ####------------------------------------------------------------------------------------------------------#### document_tree = ET.parse(self.work_dir + "/styles.xml") root = document_tree.getroot() ####################### element = root.find( '{urn:oasis:names:tc:opendocument:xmlns:office:1.0}styles') for target in element.findall( "./{urn:oasis:names:tc:opendocument:xmlns:style:1.0}style[@{urn:oasis:names:tc:opendocument:xmlns:style:1.0}name='Graphics']" ): found_it = True if ( not found_it ): ## if didn't find the element, what we are looking for, than we must make it element.append( Element( '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}style', { '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}parent-style-name': 'Graphics', '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}family': 'graphic', '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}name': graph_style_name })) for target in element.findall( "./{urn:oasis:names:tc:opendocument:xmlns:style:1.0}style[@{urn:oasis:names:tc:opendocument:xmlns:style:1.0}parent-style-name='Graphics']" ): child = target child.append( Element( '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}graphic-properties', { '{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}fill': 'none', '{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}stroke': 'none' })) found_it = False ##write into file xmlstr = ET.tostring(root) #write xml header with open(self.work_dir + "/styles.xml", "w") as text_file: text_file.write( '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>') #write xml body with open(self.work_dir + "/styles.xml", "a") as text_file: text_file.write(xmlstr) ####---------------------------END-OF-STYLE.XML----------------------------------------------------------------------------------------------### ################################################################################# ###-----------------modifying the CONTENT.XML file--------------------------------------------------------------------------------------------### ####---------------------------------------------------------------------------------------------------------------------------------------#### document_tree = ET.parse(self.work_dir + "/content.xml") root = document_tree.getroot() element = root.find( '{urn:oasis:names:tc:opendocument:xmlns:office:1.0}automatic-styles' ) for target in element.findall( "./{urn:oasis:names:tc:opendocument:xmlns:style:1.0}style[@{urn:oasis:names:tc:opendocument:xmlns:style:1.0}parent-style-name='Graphics']" ): found_it = True if ( not found_it ): ## if didn't find the element, what we are looking for, than we must make it element.append( Element( '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}style', { '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}parent-style-name': 'Graphics', '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}family': 'graphic', '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}name': graph_style_name })) for target in element.findall( "./{urn:oasis:names:tc:opendocument:xmlns:style:1.0}style[@{urn:oasis:names:tc:opendocument:xmlns:style:1.0}parent-style-name='Graphics']" ): child = target child.append( Element( '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}graphic-properties', { '{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}fill': 'none', '{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}stroke': 'none' })) found_it = False ##-----------------------inject into body section------------------------############ element = root.find( '{urn:oasis:names:tc:opendocument:xmlns:office:1.0}body' ) ##office:body spreadsheet = element.find( "{urn:oasis:names:tc:opendocument:xmlns:office:1.0}spreadsheet" ) ##office:spreadsheet table = spreadsheet.find( "{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table" ) ##office:table ##insert the row into one before last, 'couse last is row means all empty row to ending table_row = Element( '{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table-row', { '{urn:oasis:names:tc:opendocument:xmlns:table:1.0}style-name': row_used_style }) cell1 = ET.SubElement( table_row, '{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table-cell', { '{urn:oasis:names:tc:opendocument:xmlns:table:1.0}sytle-name': cell_used_style }) draw_frame = ET.SubElement( cell1, '{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}frame', { '{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}id': draw_id, '{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}name': picture_name, '{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}style-name': graph_style_name, '{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}z-index': '1', '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}rel-height': 'scale', '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}rel-width': 'scale', '{urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0}height': '5.53125in', '{urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0}width': '8.33333in', '{urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0}x': '0in', '{urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0}y': '0in' }) draw_image = ET.SubElement( draw_frame, '{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}image', { '{http://www.w3.org/1999/xlink}actuate': 'onLoad', '{http://www.w3.org/1999/xlink}href': self.bait, '{http://www.w3.org/1999/xlink}show': 'embed', '{http://www.w3.org/1999/xlink}type': 'simple' }) title = ET.SubElement( draw_frame, '{urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0}title') desc = ET.SubElement( draw_frame, '{urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0}desc') cell2 = ET.SubElement( table_row, '{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table-cell', { '{urn:oasis:names:tc:opendocument:xmlns:table:1.0}number-columns-repeated': '16383' }) table.insert(len(table) - 1, table_row) for target in table.findall( "{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table-row" ): ##in the last row is the nr of empty rows last_table = target if (not (last_table == '')): print last_table.attrib.get( '{urn:oasis:names:tc:opendocument:xmlns:table:1.0}number-rows-repeated' ) if (not (last_table.attrib.get( '{urn:oasis:names:tc:opendocument:xmlns:table:1.0}number-rows-repeated' ) == None)): key_nr = int( last_table.attrib.get( '{urn:oasis:names:tc:opendocument:xmlns:table:1.0}number-rows-repeated' )) key_nr = int(key_nr) - 2 else: key_nr = 1000 last_table.attrib[ '{urn:oasis:names:tc:opendocument:xmlns:table:1.0}number-rows-repeated'] = str( key_nr) ##decrease the empty row nr with 2, the size of the picture ##write into file xmlstr = ET.tostring(root) #write xml header with open(self.work_dir + "/content.xml", "w") as text_file: text_file.write( '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>') #write xml body with open(self.work_dir + "/content.xml", "a") as text_file: text_file.write(xmlstr) self.zipdir(self.work_dir, self.outputfile) return True #namepsaces for odt from LibreOffice + some for MO ET.register_namespace('office', "urn:oasis:names:tc:opendocument:xmlns:office:1.0") ET.register_namespace('style', "urn:oasis:names:tc:opendocument:xmlns:style:1.0") ET.register_namespace('text', "urn:oasis:names:tc:opendocument:xmlns:text:1.0") ET.register_namespace('table', "urn:oasis:names:tc:opendocument:xmlns:table:1.0") ET.register_namespace('draw', "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0") ET.register_namespace( 'fo', "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0") ET.register_namespace('xlink', "http://www.w3.org/1999/xlink") ET.register_namespace('dc', "http://purl.org/dc/elements/1.1/") ET.register_namespace('meta', "urn:oasis:names:tc:opendocument:xmlns:meta:1.0") ET.register_namespace( 'number', "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0") ET.register_namespace( 'svg', "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0") ET.register_namespace('chart', "urn:oasis:names:tc:opendocument:xmlns:chart:1.0") ET.register_namespace('dr3d', "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0") ET.register_namespace('math', "http://www.w3.org/1998/Math/MathML") ET.register_namespace('form', "urn:oasis:names:tc:opendocument:xmlns:form:1.0") ET.register_namespace('script', "urn:oasis:names:tc:opendocument:xmlns:script:1.0") ET.register_namespace('ooo', "http://openoffice.org/2004/office") ET.register_namespace('ooow', "http://openoffice.org/2004/writer") ET.register_namespace('oooc', "http://openoffice.org/2004/calc") ET.register_namespace('dom', "http://www.w3.org/2001/xml-events") ET.register_namespace('xforms', "http://www.w3.org/2002/xforms") ET.register_namespace('xsd', "http://www.w3.org/2001/XMLSchema") ET.register_namespace('xsi', "http://www.w3.org/2001/XMLSchema-instance") ET.register_namespace('rpt', "http://openoffice.org/2005/report") ET.register_namespace('of', "urn:oasis:names:tc:opendocument:xmlns:of:1.2") ET.register_namespace('xhtml', "http://www.w3.org/1999/xhtml") ET.register_namespace('grddl', "http://www.w3.org/2003/g/data-view#") ET.register_namespace('tableooo', "http://openoffice.org/2009/table") ET.register_namespace( 'field', "urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0") ET.register_namespace( 'formx', "urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0") ET.register_namespace('css3t', "http://www.w3.org/TR/css3-text/") ET.register_namespace('msoxl', "http://schemas.microsoft.com/office/excel/formula")
def register_nsmap(): for prefix, uri in NSMAP.items(): prefix_no_xmlns = prefix.replace("xmlns", "").replace(":", "") ETree.register_namespace(prefix_no_xmlns, uri)
def create_sheet6(basin, period, unit, data, output, template=False): """ Create sheet 6 of the Water Accounting Plus framework. Parameters ---------- basin : str The name of the basin. period : str The period of analysis. units : str the unit of the data on sheet 6. data : str csv file that contains the water data. The csv file has to follow an specific format. A sample csv is available here: https://github.com/wateraccounting/wa/tree/master/Sheets/csv output : list Filehandles pointing to the jpg files to be created. template : str or boolean, optional the svg file of the sheet. False uses the standard svg files. Default is False. Examples -------- >>> from wa.Sheets import * >>> create_sheet6(basin='Helmand', period='2007-2011', units = 'km3/yr', data = r'C:\Sheets\csv\Sample_sheet6.csv', output = r'C:\Sheets\sheet_6.png') """ df1 = pd.read_csv(data, sep=';') p1 = dict() p1['VR_forest'] = float( df1.loc[(df1.TYPE == 'Forests') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VR_shrubland'] = float( df1.loc[(df1.TYPE == 'Shrubland') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VR_naturalgrassland'] = float( df1.loc[(df1.TYPE == 'Natural Grasslands') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VR_naturalwaterbodies'] = float( df1.loc[(df1.TYPE == 'Natural Water Bodies') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VR_wetlands'] = float( df1.loc[(df1.TYPE == 'Wetlands') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VR_rainfedcrops'] = float( df1.loc[(df1.TYPE == 'Rainfed Crops') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VR_forestplantations'] = float( df1.loc[(df1.TYPE == 'Forest Plantations') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VR_irrigatedcrops'] = float( df1.loc[(df1.TYPE == 'Irrigated crops') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VR_managedwaterbodies'] = float( df1.loc[(df1.TYPE == 'Managed water bodies') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VR_residential'] = float( df1.loc[(df1.TYPE == 'Residential') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VR_industry'] = float( df1.loc[(df1.TYPE == 'Industry') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VR_other'] = float( df1.loc[(df1.TYPE == 'Other (Non-Manmade)') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VR_managedaquiferrecharge'] = float( df1.loc[(df1.TYPE == 'NON_LU_SPECIFIC') & (df1.SUBTYPE == 'ManagedAquiferRecharge')].VALUE) p1['VR_glaciers'] = float( df1.loc[(df1.TYPE == 'Glaciers') & (df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VGW_forest'] = float( df1.loc[(df1.TYPE == 'Forests') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['VGW_shrubland'] = float( df1.loc[(df1.TYPE == 'Shrubland') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['VGW_rainfedcrops'] = float( df1.loc[(df1.TYPE == 'Rainfed Crops') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['VGW_forestplantations'] = float( df1.loc[(df1.TYPE == 'Forest Plantations') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['VGW_wetlands'] = float( df1.loc[(df1.TYPE == 'Wetlands') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['VGW_naturalgrassland'] = float( df1.loc[(df1.TYPE == 'Natural Grasslands') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['VGW_othernatural'] = float( df1.loc[(df1.TYPE == 'Other (Non-Manmade)') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['VGW_irrigatedcrops'] = float( df1.loc[(df1.TYPE == 'Irrigated crops') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['VGW_industry'] = float( df1.loc[(df1.TYPE == 'Industry') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['VGW_aquaculture'] = float( df1.loc[(df1.TYPE == 'Aquaculture') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['VGW_residential'] = float( df1.loc[(df1.TYPE == 'Residential') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['VGW_greenhouses'] = float( df1.loc[(df1.TYPE == 'Greenhouses') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['VGW_othermanmade'] = float( df1.loc[(df1.TYPE == 'Other') & (df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['RFG_irrigatedcrops'] = float( df1.loc[(df1.TYPE == 'Irrigated crops') & (df1.SUBTYPE == 'RETURN_FLOW_GROUNDWATER')].VALUE) p1['RFG_industry'] = float( df1.loc[(df1.TYPE == 'Industry') & (df1.SUBTYPE == 'RETURN_FLOW_GROUNDWATER')].VALUE) p1['RFG_aquaculture'] = float( df1.loc[(df1.TYPE == 'Aquaculture') & (df1.SUBTYPE == 'RETURN_FLOW_GROUNDWATER')].VALUE) p1['RFG_residential'] = float( df1.loc[(df1.TYPE == 'Residential') & (df1.SUBTYPE == 'RETURN_FLOW_GROUNDWATER')].VALUE) p1['RFG_greenhouses'] = float( df1.loc[(df1.TYPE == 'Greenhouses') & (df1.SUBTYPE == 'RETURN_FLOW_GROUNDWATER')].VALUE) p1['RFG_other'] = float( df1.loc[(df1.TYPE == 'Other') & (df1.SUBTYPE == 'RETURN_FLOW_GROUNDWATER')].VALUE) p1['RFS_forest'] = float( df1.loc[(df1.TYPE == 'Forests') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['RFS_shrubland'] = float( df1.loc[(df1.TYPE == 'Shrubland') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['RFS_rainfedcrops'] = float( df1.loc[(df1.TYPE == 'Rainfed Crops') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['RFS_forestplantations'] = float( df1.loc[(df1.TYPE == 'Forest Plantations') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['RFS_wetlands'] = float( df1.loc[(df1.TYPE == 'Wetlands') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['RFS_naturalgrassland'] = float( df1.loc[(df1.TYPE == 'Natural Grasslands') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['RFS_othernatural'] = float( df1.loc[(df1.TYPE == 'Other (Non-Manmade)') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['RFS_irrigatedcrops'] = float( df1.loc[(df1.TYPE == 'Irrigated crops') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['RFS_industry'] = float( df1.loc[(df1.TYPE == 'Industry') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['RFS_aquaculture'] = float( df1.loc[(df1.TYPE == 'Aquaculture') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['RFS_residential'] = float( df1.loc[(df1.TYPE == 'Residential') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['RFS_greenhouses'] = float( df1.loc[(df1.TYPE == 'Greenhouses') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['RFS_othermanmade'] = float( df1.loc[(df1.TYPE == 'Other') & (df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['VRtotal_natural'] = pd.np.nansum( df1.loc[(df1.SUBTYPE == 'VERTICAL_RECHARGE')].VALUE) p1['VRtotal_manmade'] = float( df1.loc[(df1.SUBTYPE == 'ManagedAquiferRecharge')].VALUE) p1['VRtotal'] = pd.np.nansum( [p1['VRtotal_natural'], p1['VRtotal_manmade']]) p1['CRtotal'] = float(df1.loc[(df1.SUBTYPE == 'CapillaryRise')].VALUE) #p1['delta_S'] = float(df1.loc[(df1.SUBTYPE == 'DeltaS')].VALUE) p1['VGWtotal_natural'] = pd.np.nansum([ p1['VGW_forest'], p1['VGW_shrubland'], p1['VGW_rainfedcrops'], p1['VGW_forestplantations'], p1['VGW_wetlands'], p1['VGW_naturalgrassland'], p1['VGW_othernatural'] ]) p1['VGWtotal_manmade'] = pd.np.nansum([ p1['VGW_irrigatedcrops'], p1['VGW_industry'], p1['VGW_aquaculture'], p1['VGW_residential'], p1['VGW_greenhouses'], p1['VGW_othermanmade'] ]) p1['VGWtotal'] = pd.np.nansum( df1.loc[(df1.SUBTYPE == 'VERTICAL_GROUNDWATER_WITHDRAWALS')].VALUE) p1['RFGtotal_manmade'] = p1['RFGtotal'] = pd.np.nansum( df1.loc[(df1.SUBTYPE == 'RETURN_FLOW_GROUNDWATER')].VALUE) p1['RFStotal_natural'] = pd.np.nansum([ p1['RFS_forest'], p1['RFS_shrubland'], p1['RFS_rainfedcrops'], p1['RFS_forestplantations'], p1['RFS_wetlands'], p1['RFS_naturalgrassland'], p1['RFS_othernatural'] ]) p1['RFStotal_manmade'] = pd.np.nansum([ p1['RFS_irrigatedcrops'], p1['RFS_industry'], p1['RFS_aquaculture'], p1['RFS_residential'], p1['RFS_greenhouses'], p1['RFS_othermanmade'] ]) p1['RFStotal'] = pd.np.nansum( df1.loc[(df1.SUBTYPE == 'RETURN_FLOW_SURFACEWATER')].VALUE) p1['HGI'] = float(df1.loc[(df1.TYPE == 'NON_LU_SPECIFIC') & (df1.SUBTYPE == 'GWInflow')].VALUE) p1['HGO'] = float(df1.loc[(df1.TYPE == 'NON_LU_SPECIFIC') & (df1.SUBTYPE == 'GWOutflow')].VALUE) p1['baseflow'] = float(df1.loc[(df1.TYPE == 'NON_LU_SPECIFIC') & (df1.SUBTYPE == 'Baseflow')].VALUE) p1['delta_S'] = p1['VRtotal'] - p1['CRtotal'] - p1['VGWtotal'] + p1[ 'RFGtotal_manmade'] + p1['RFStotal'] - p1['baseflow'] #p1['CRtotal'] = p1['VRtotal'] - p1['VGWtotal'] + p1['RFGtotal_manmade'] + p1['RFStotal'] - p1['baseflow'] - p1['delta_S'] if not template: path = os.path.dirname(os.path.abspath(__file__)) svg_template_path_1 = os.path.join(path, 'svg', 'sheet_6.svg') else: svg_template_path_1 = os.path.abspath(template) tree1 = ET.parse(svg_template_path_1) xml_txt_box = tree1.findall('''.//*[@id='basin']''')[0] xml_txt_box.getchildren()[0].text = 'Basin: ' + basin xml_txt_box = tree1.findall('''.//*[@id='period']''')[0] xml_txt_box.getchildren()[0].text = 'Period: ' + period xml_txt_box = tree1.findall('''.//*[@id='unit']''')[0] xml_txt_box.getchildren()[0].text = 'Sheet 6: Groundwater ({0})'.format( unit) for key in p1.keys(): xml_txt_box = tree1.findall(".//*[@id='{0}']".format(key))[0] if not pd.isnull(p1[key]): xml_txt_box.getchildren()[0].text = '%.1f' % p1[key] else: xml_txt_box.getchildren()[0].text = '-' ET.register_namespace("", "http://www.w3.org/2000/svg") tempout_path = output.replace('.png', '_temporary.svg') tree1.write(tempout_path) subprocess.call([ 'C:\Program Files\Inkscape\inkscape.exe', tempout_path, '--export-png=' + output, '-d 300' ]) os.remove(tempout_path)
def createFileButtonClicked(self): #Used for creating the files from the combobox choices # Get combobox values vehicle = self.vehicleComboBox.currentText() module = self.moduleComboBox.currentText() hardware = self.hardwareComboBox.currentText() prevValue = self.valueComboBox.currentText() newValue = self.fileLineEdit.text() newPath = path + vehicle + "\\" # getthe path for the new file and the previous file prevFilePath = glob.glob(newPath + hardware + "*" + module + "*" + prevValue + ".xml")[0] prevFile = prevFilePath.split("\\") prevFile = prevFile[len(prevFile) - 1].split(".xml")[0] newFilePath = newPath + newValue + ".xml" newFile = newFilePath.split("\\") newFile = newFile[len(newFile) - 1].split(".xml")[0] # Register the namespace for the ivs files ET.register_namespace( 'ivs', 'platform:/resource/com.avl.ditest.dicore.ivs/model/ivs.xsd') #Open the previous file and parse through it prevFileXML = ET.parse(prevFilePath) prevFileRoot = prevFileXML.getroot() # If theres a successor in the file then open the successor # and set the predecessor value to be the new file successor = "" if "successorPartNumber" in prevFileRoot.attrib: successor = prevFileRoot.attrib["successorPartNumber"] successorFilePath = newPath + successor + ".xml" successorFileXML = ET.parse(successorFilePath) successorFileRoot = successorFileXML.getroot() successorFileRoot.set('predecessorPartNumber', newFile.split(".")[0]) successorFileXML.write(successorFilePath, encoding='utf-8', xml_declaration=True) #Set the previousfile successor to be the new one prevFileRoot.set('successorPartNumber', newFile) # Save the previous file prevFileXML.write(prevFilePath, encoding='utf-8', xml_declaration=True) #NOW WE USE THE PREVIOUS FILE FOR THE NEW ONE # If their is a successor then add the part number to the file if successor != "": prevFileRoot.set('successorPartNumber', successor) else: # If not then remove it from the board prevFileRoot.attrib.pop('successorPartNumber', None) # Set the predecessor value prevFileRoot.set('predecessorPartNumber', prevFile) # Set the partnumber created earlier prevFileRoot.set('assyPN', newFile) # Save the file to the new file path prevFileXML.write(newFilePath, encoding='utf-8', xml_declaration=True) QtWidgets.QMessageBox.about(None, "Created", "File Created Succesfully") #Initalise the update area box self.initaliseUpdateComboBox()
def _addListElements(self, parent, name, values): for value in values: el = ET.SubElement(parent, "{{{0}}}{1}".format(self.NS, name)) el.text = value def _addDictionaryElements(self, parent, name, values): # Sort keys so we have a stable order of items for testing. # Alternative would be SortedDict, but is >=2.7 for k in sorted(values.keys()): el = ET.SubElement(parent, "{{{0}}}{1}".format(self.NS, name)) el.set("rel", k) el.text = values[k] # Avoid namespace prefixes, VLC doesn't like it if hasattr(ET, 'register_namespace'): ET.register_namespace('', XspfBase.NS) # in-place prettyprint formatter # From http://effbot.org/zone/element-lib.htm def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else:
def test_all(): _logger = logging.getLogger(os.path.basename(__file__)) logging.basicConfig(level=logging.DEBUG) XMLNS_TEST_CLAMSCAN = "file:///opt/local/bin/clamscan" XMLNS_TEST_UNREGGED = "file:///dev/random" ET.register_namespace("clam", XMLNS_TEST_CLAMSCAN) fi = Objects.FileObject() fi.filename = "clamscanned" #Try and fail to add a non-Element to the list. failed = None _logger.debug("Before: " + repr(fi.externals)) try: fi.externals.append(1) failed = False except TypeError: failed = True except: failed = True raise _logger.debug("After: " + repr(fi.externals)) assert failed failed = None #Dummy up a non-DFXML namespace element. This should be appendable. e = ET.Element("{%s}scan_results" % XMLNS_TEST_CLAMSCAN) e.text = "Clean" fi.externals.append(e) #Dummy up a DFXML namespace element. This should not be appendable (the schema specifies other namespaces). e = ET.Element("{%s}filename" % Objects.dfxml.XMLNS_DFXML) e.text = "Superfluous name" _logger.debug("Before: " + repr(fi.externals)) try: fi.externals.append(e) failed = False except ValueError: failed = True except: failed = True raise _logger.debug("After: " + repr(fi.externals)) assert failed failed = None #Add an element with the colon prefix style e = ET.Element("clam:version") e.text = "20140101" fi.externals.append(e) #Add an element that doesn't have an ET-registered namespace prefix. e = ET.Element("{%s}test2" % XMLNS_TEST_UNREGGED) e.text = "yes" fi.externals.append(e) #Test serialization s = Objects._ET_tostring(fi.to_Element( )) #TODO Maybe this should be more than an internal function. _logger.debug(s) if s.find("scan_results") == -1: raise ValueError( "Serialization did not output other-namespace element 'scan_results'." ) if s.find("clam:version") == -1: raise ValueError( "Serialization did not output prefixed element 'clam:version'.") if s.find("test2") == -1: raise ValueError( "Serialization did not output unregistered-prefix element 'test2'." ) #Test de-serialization fir = Objects.FileObject() x = ET.XML(s) fir.populate_from_Element(x) _logger.debug("De-serialized: %r." % fir.externals) assert len(fir.externals) == 3
#!/usr/bin/env python3 from xml.etree import ElementTree tree = ElementTree.parse("in.kml") #名前空間の再定義 ElementTree.register_namespace('', 'http://earth.google.com/kml/2.0') for node in tree.findall( ".//hoge:PolyStyle/hoge:color", namespaces={'hoge': 'http://earth.google.com/kml/2.0'}): # 内容書き換え node.text = "AA001122" tree.write("out.kml", "UTF-8", True)
def execute(game, channel, decompileDir, packageName): log_utils.debug("now to execute post_script") manifest = decompileDir + '/AndroidManifest.xml' ET.register_namespace('android', androidNS) key = '{' + androidNS + '}name' name = key keyVal = '{' + androidNS + '}value' pLevel = '{' + androidNS + '}protectionLevel' tree = ET.parse(manifest) root = tree.getroot() appNode = root.find('application') if appNode is None: return 1 #设置包名和权限 log_utils.debug("now to change permission and meta-data") permissionLst = root.findall('permission') if permissionLst: for p in permissionLst: pname = p.get(name) if pname == 'com.yxg.juhe.permission.JPUSH_MESSAGE': p.set(name, packageName + ".permission.JPUSH_MESSAGE") break upermissionLst = root.findall('uses-permission') if upermissionLst: for p in upermissionLst: pname = p.get(name) if pname == 'com.yxg.juhe.permission.JPUSH_MESSAGE': p.set(name, packageName + ".permission.JPUSH_MESSAGE") break metaLst = appNode.findall('meta-data') if metaLst: for p in metaLst: pname = p.get(name) if pname == 'CASTLE_PACKAGE_NAME': p.set(keyVal, packageName) break for p in metaLst: pname = p.get(name) if pname == 'JPUSH_APPKEY': appNode.remove(p) #设置包名和权限 #替换包名 log_utils.debug("now to change packageName") activityNodeLst = appNode.findall('activity') if activityNodeLst is None: return for activityNode in activityNodeLst: activityName = activityNode.get(name) if activityName == 'cn.jpush.android.ui.PushActivity': intentFilters = activityNode.findall('intent-filter') for intentNode in intentFilters: categoryNodeLst = intentNode.findall('category') if categoryNodeLst is None: break for categoryNode in categoryNodeLst: if categoryNode.attrib[key] == 'com.yxg.juhe': categoryNode.set(key, packageName) break serviceNodeLst = appNode.findall('service') if serviceNodeLst is None: return for serviceNode in serviceNodeLst: serviceName = serviceNode.get(name) if serviceName == 'cn.jpush.android.service.DaemonService': intentFilters = serviceNode.findall('intent-filter') for intentNode in intentFilters: categoryNodeLst = intentNode.findall('category') if categoryNodeLst is None: break for categoryNode in categoryNodeLst: if categoryNode.attrib[key] == 'com.yxg.juhe': categoryNode.set(key, packageName) break receiverNodeLst = appNode.findall('receiver') if receiverNodeLst is None: return for receiverNode in receiverNodeLst: receiverName = receiverNode.get(name) if receiverName == 'cn.jpush.android.service.PushReceiver': intentFilters = receiverNode.findall('intent-filter') for intentNode in intentFilters: actionNodeLst = intentNode.findall('action') if actionNodeLst is None: break bFindAction = False for actionNode in actionNodeLst: if actionNode.attrib[ key] == 'cn.jpush.android.intent.NOTIFICATION_RECEIVED_PROXY': bFindAction = True break if bFindAction: categoryNodeLst = intentNode.findall('category') if categoryNodeLst is None: break for categoryNode in categoryNodeLst: if categoryNode.attrib[key] == 'com.yxg.juhe': categoryNode.set(key, packageName) break elif receiverName == 'com.Castle.jpushjar.JPushReceiver': intentFilters = receiverNode.findall('intent-filter') for intentNode in intentFilters: categoryNodeLst = intentNode.findall('category') if categoryNodeLst is None: break for categoryNode in categoryNodeLst: if categoryNode.attrib[key] == 'com.yxg.juhe': categoryNode.set(key, packageName) break break #替换包名结束 #读取jpush_keys文件中的JPUSH_APPKEY log_utils.debug("now to set JPUSH_APPKEY") configFile = file_utils.getFullPath('games/' + game['appName'] + '/jpush_keys.properties') if not os.path.exists(configFile): log_utils.debug("jpush_keys file not exists." + configFile) return 1 f = open(configFile, 'r') for line in f.readlines(): item = line.strip().split('=') if item[0] == channel['id']: metaDataNode = SubElement(appNode, 'meta-data') metaDataNode.set(key, 'JPUSH_APPKEY') metaDataNode.set(keyVal, item[1]) break f.close() #JPUSH_APPKEY处理完毕 tree.write(manifest, 'UTF-8') log_utils.debug("post_script execute successfully") return 0
symbols = { 'heating', 'setting', 'user', 'room', 'alert', 'squeezebox', 'light', } symbol_count = 0 mypath = '/etc/openhab2/html/habpanel/svg/original/section/' onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] ET.register_namespace("", "http://www.w3.org/2000/svg") top = ET.Element('svg', attrib={ 'version': '1.1', 'xmlns:xlink': 'http://www.w3.org/1999/xlink', 'x': "0px", 'y': "0px", 'viewBox': "0 0 48 48", 'enable-background': "new 0 0 48 48", 'xml:space': "preserve" }) comment = ET.Comment('Generated by SVG-Combiner') top.append(comment) for file in onlyfiles: if (file[:1] != '.'):
import xml.etree.ElementTree as ET from argparse import ArgumentParser from random import random, randint from threading import Thread from time import sleep from src.communication import messages from src.communication.client import Client from src.communication.helpful_math import Manhattan_Distance as manhattan from src.communication.info import GameInfo, Direction, Allegiance, PieceInfo, PieceType, \ GoalFieldType, ClientTypeTag, PlayerType, PlayerInfo from src.communication.unexpected import UnexpectedServerMessage GAME_SETTINGS_TAG = "{https://se2.mini.pw.edu.pl/17-pl-19/17-pl-19/}" XML_MESSAGE_TAG = "{https://se2.mini.pw.edu.pl/17-results/}" ET.register_namespace('', "https://se2.mini.pw.edu.pl/17-results/") def parse_game_master_settings(): full_file = os.getcwd() + "\GameMasterSettings.xml" tree = ET.parse(full_file) root = tree.getroot() return root class GameMaster(Client): def parse_game_definition(self): root = parse_game_master_settings() self.keep_alive_interval = int(root.attrib.get('KeepAliveInterval'))
help='input filename') parser.add_argument('-d', '--circle_diameter', type=float, default=2, help='input filename') args = parser.parse_args() f_in_name = args.input d = args.circle_diameter f_out_name = 'mod_{}'.format(f_in_name) f_out_holes_name = 'holes_{}'.format(f_in_name) ET.register_namespace('', 'http://purl.org/dc/elements/1.1/') ET.register_namespace('', 'http://creativecommons.org/ns#') ET.register_namespace('', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#') ET.register_namespace('', 'http://www.w3.org/2000/svg') tree = ET.parse(f_in_name) root = tree.getroot() white_circle_list = [] white_circle_cent = [] path_0_list = [] height = float(root.attrib['height'].split('mm')[0]) print(height) for child in root:
file.close() def createLegsFile(createlegsfileArgs): avgLength = createlegsfileArgs.totalDistance / createlegsfileArgs.numLegs with open(createlegsfileArgs.outfile, 'w') as outfile: for i in range(createlegsfileArgs.numLegs): outfile.write(str((i + 1) * avgLength) + "\n") # # # # Register our namespace so the output looks ok ET.register_namespace('', "http://www.topografix.com/GPX/1/1") # And parse all the args for our 2 sub commands parser = argparse.ArgumentParser(description='Tools to help slice a GPX file') subparsers = parser.add_subparsers(help='sub-command help') sliceParser = subparsers.add_parser('slice', help='Slice a GPX file') sliceParser.add_argument("infile", type=argparse.FileType('r'), help="GPX filename to process") sliceParser.add_argument('legDistancesFile', type=argparse.FileType('r'), help='leg distances file name') sliceParser.add_argument('outfile', help='output file name') sliceParser.set_defaults(func=slice)
def save_as_pnml(self, filename): """Save PN in PNML format to [filename]. [filename]: file or filename in which the PN has to be written""" own_fid = False if isinstance(filename, basestring): #a filename file = open(filename, 'w') self.filename = filename own_fid = True else: file = filename self.filename = file.name if not self.gp_name[self.g]: self.gp_name[self.g] = self.filename def add_text(element, text): xmltree.SubElement( element, '{http://www.pnml.org/version-2009/grammar/pnml}text' ).text = text def add_name(element, text): add_text( xmltree.SubElement( element, '{http://www.pnml.org/version-2009/grammar/pnml}name'), text) xmltree.register_namespace( "pnml", "http://www.pnml.org/version-2009/grammar/pnml") root = xmltree.Element( '{http://www.pnml.org/version-2009/grammar/pnml}pnml') net = xmltree.SubElement( root, '{http://www.pnml.org/version-2009/grammar/pnml}net', { '{http://www.pnml.org/version-2009/grammar/pnml}id': 'net1', '{http://www.pnml.org/version-2009/grammar/pnml}type': 'http://www.pnml.org/version-2009/grammar/pnmlcoremodel' }) add_name(net, self.gp_name[self.g]) page = xmltree.SubElement( net, '{http://www.pnml.org/version-2009/grammar/pnml}page', {'{http://www.pnml.org/version-2009/grammar/pnml}id': 'n0'}) node_num = 1 id_map = {} for p in self.get_places(names=False): name = self.vp_elem_name[p] xml_id = "n%d" % node_num node = xmltree.SubElement( page, '{http://www.pnml.org/version-2009/grammar/pnml}place', {'{http://www.pnml.org/version-2009/grammar/pnml}id': xml_id}) add_name(node, name) tokens = self.vp_place_initial_marking[p] if tokens >= 1: marking = xmltree.SubElement( node, '{http://www.pnml.org/version-2009/grammar/pnml}initialMarking' ) add_text(marking, str(tokens)) id_map[p] = xml_id node_num += 1 for t in self.get_transitions(names=False): assert t not in id_map name = self.vp_elem_name[t] if self.vp_transition_dummy[t]: name = '' # empty label for dummies xml_id = "n%d" % node_num node = xmltree.SubElement( page, '{http://www.pnml.org/version-2009/grammar/pnml}transition', {'{http://www.pnml.org/version-2009/grammar/pnml}id': xml_id}) add_name(node, name) id_map[t] = xml_id node_num += 1 for e in self.g.edges(): xml_id = "arc%d" % node_num node = xmltree.SubElement( page, '{http://www.pnml.org/version-2009/grammar/pnml}arc', { '{http://www.pnml.org/version-2009/grammar/pnml}id': xml_id, '{http://www.pnml.org/version-2009/grammar/pnml}source': id_map[e.source()], '{http://www.pnml.org/version-2009/grammar/pnml}target': id_map[e.target()] }) add_name(node, "%d" % self.ep_edge_weight[e]) node_num += 1 tree = xmltree.ElementTree(root) tree.write( file, encoding='UTF-8', xml_declaration=True, default_namespace='http://www.pnml.org/version-2009/grammar/pnml') self.last_write_format = 'pnml' self.mark_as_modified(False) if own_fid: file.close()
def write(final_names, final_titles, file, output, log_file, filename): folder = 'Webapp/Files/results' if not os.path.exists(folder): os.makedirs(folder) clear_files(filename) print('writing ' + filename) #adding BIBFRAME namespaces enhanched = ETree.register_namespace( 'bf', 'http://id.loc.gov/ontologies/bibframe/') enhanched = ETree.register_namespace('bflc', 'http://id.loc.gov/ontologies/bflc/') enhanched = ETree.register_namespace( 'rdfs', 'http://www.w3.org/2000/01/rdf-schema#') enhanched = ETree.register_namespace( 'rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#') enhanched = ETree.register_namespace('madsrdf', 'http://www.loc.gov/mads/rdf/v1#') enhanched = ETree.parse(file) clear_TSV(filename) #writing extract names matching URIs into a TSV file tsv_file = 'Webapp/Files/results/%s/TSVs/URIs-%s.tsv' % (filename, filename) with open(tsv_file, "a") as tsv: tsv.write("ingest key" + "\t" + "viaf ID" + "\t" + "LC ID" + "\n") print("writing enriched names") for key in final_names.keys(): name = key.split('-_-_-')[0] try: #if the key (i.e. LCID or VIAF ID) exists for a certain name, create the URI if "LC" in final_names[key]['scores'].keys(): LC = 'http://id.loc.gov/authorities/names/' + ( final_names[key]['scores']['LC'][0]) if "VIAF" in final_names[key]['scores'].keys(): VF = 'http://viaf.org/viaf/' + ( final_names[key]['scores']['VIAF'][0]) #itterate over the extracted keys (names) for k in final_names[key]['keys']: uri_key = k tsv.write(uri_key + "\t" + VF + "\t" + LC + "\n") root = enhanched.getroot() #search the XML for "bf:agent", if the 'example.org' key matches, insert the VF/LC URI for element in root.iter( '{http://id.loc.gov/ontologies/bibframe/}Agent'): for ku in element.attrib.keys(): if element.attrib[ku] == uri_key: element.set( '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}about', LC) #add the VF element a = ETree.SubElement(element, 'bf:identifiedBy') b = ETree.SubElement(a, 'bf:IdentifiedBy') c = ETree.SubElement(b, 'rdf:value') c.set( '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}about', VF) except: print("could not find identfier for " + key) PrintException(log_file, name) print("writing enriched titles") #itterate over the extracted keys (titles) for title in final_titles.keys(): try: if "oclcid" in final_titles[title]['scores'].keys(): OCLC_ID = final_titles[title]['scores']['oclcid'][0] if "work_id" in final_titles[title]['scores'].keys(): work_ID = final_titles[title]['scores']['work_id'][0] for k in final_titles[title]['keys']: uri_key = k tsv.write(uri_key + "\t" + OCLC_ID + "\t" + work_ID + "\n") #search the XML for "bf:Work", if the 'example.org' key matches, insert the OCLC URI root = enhanched.getroot() for element in root.iter( '{http://id.loc.gov/ontologies/bibframe/}Work'): for ku in element.attrib.keys(): if uri_key in element.attrib[ku]: element.set( '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}about', work_ID) except: print("could not find identfier for " + title) PrintException(log_file, name) out = "Webapp/Files/results/%s/enhanced-files/%s" % (filename, output) enhanched.write(out)
illegal_xml_re = re.compile("[%s]" % "".join(illegal_ranges)) #: Commonly used namespaces, and abbreviations, used by `ns_tag`. NAMESPACES = { "dc": "http://purl.org/dc/elements/1.1/", "upnp": "urn:schemas-upnp-org:metadata-1-0/upnp/", "": "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/", "ms": "http://www.sonos.com/Services/1.1", "r": "urn:schemas-rinconnetworks-com:metadata-1-0/", } # Register common namespaces to assist in serialisation (avoids the ns:0 # prefixes in XML output ) for prefix, uri in NAMESPACES.items(): XML.register_namespace(prefix, uri) def ns_tag(ns_id, tag): """Return a namespace/tag item. Args: ns_id (str): A namespace id, eg ``"dc"`` (see `NAMESPACES`) tag (str): An XML tag, eg ``"author"`` Returns: str: A fully qualified tag. The ns_id is translated to a full name space via the :const:`NAMESPACES` constant::
import xml.etree.ElementTree as ET import copy #from lxml import etree as lxmletree from xml.dom import minidom as minidom from natsort import natsorted, ns WRITE_FILE_NAME = "../src/filename.xml" ET.register_namespace('', "http://soap.sforce.com/2006/04/metadata") tree = ET.parse('../src/package.xml') root = tree.getroot() writeRoot = copy.deepcopy(root) for elem in writeRoot: if 'types' in elem.tag: elem.clear() membersDict = {} for elem in root: membersSet = set([]) for subelem in elem: if ('members' in subelem.tag): membersSet.add(subelem.text) elif ('name' in subelem.tag): membersDict[subelem.text] = membersSet break writeList = [] for key in membersDict: innerList = natsorted(membersDict[key], alg=ns.IGNORECASE) #innerList = sorted(membersDict[key]) innerList.append(key)