def convert(self, data, cache, **kwargs): bodydom = Element('div') kmldom = XML(data) ns = kmldom.tag.strip('kml') placemarks = kmldom.findall('.//%sPlacemark' % ns) for placemark in placemarks: titles = placemark.findall(ns + 'name') for title in titles: t = Element('h2') t.text = title.text bodydom.append(t) descriptions = placemark.findall(ns + 'description') for desc in descriptions: if desc.text: try: text = desc.text.encode('ascii', 'xmlcharrefreplace').strip() except: text = desc.text.strip() text = sanitize(text) d = XML('<div>' + text.encode('ascii', 'xmlcharrefreplace') + '</div>') bodydom.append(d) body = tostring(bodydom) cache.setData(body) return cache
def saveScriptConfig(config): """ save it into the the config """ elemConfig = Element("config") lognode = Element("logvalue") elemConfig.append(lognode) lognode.text = str(config.logvalue) mediaNode = Element("media") mediaNode.attrib["updateurl"] = config.mediaUpdateURL elemConfig.append(mediaNode) podcastNode = Element("podcast") if config.podcastDownload: podcastNode.attrib["download"] = 'true' else: podcastNode.attrib["download"] = 'false' podcastNode.attrib["localpath"] = config.podcastDownloadPath elemConfig.append(podcastNode) # create the userdata dir when not exist if not os.path.exists(CONFIG_DIR_ROOT): createDirectory(CONFIG_DIR_ROOT, recursive=True) #if os.path.exists(CONFIG_DIR): createXmlFile(CONFIG_FULL_PATH, elemConfig) #, encoding='ascii')
def addRing(self, objRing, strType): if strType == 'Inner': elemBnd = Element('innerBoundaryIs') else: elemBnd = Element('outerBoundaryIs') elemRing = SubElement(elemBnd, 'LinearRing') elemCoords = SubElement(elemRing, "coordinates") elemCoords.text = self.addCoordinates(objRing[1]) return elemBnd
def create_new_feature(self, location=None): self.feature = Element('feature') for elem in self.tag_names: self.feature.append(Element(elem)) if not location: self.xmltree.append(self.feature) else: self.xmltree.insert(location, self.feature) self.indent(self.xmltree)
def new_tree_term(self, termIdentifier, caption, description): term = Element(NS + 'term') treeTermIdentifier = Element(NS + 'termIdentifier') treeTermIdentifier.text = termIdentifier term.append(treeTermIdentifier) treeCaption = Element(NS + 'caption') self.addLangs(treeCaption, caption) term.append(treeCaption) treeDesc = Element('description') self.addLangs(treeDesc, description) term.append(treeDesc) return term
def maketree(printdict): root=Element('top') i=0 for (session, no, house) in printdict.keys(): i=i+1 elem=Element('print',printdict[(session, no, house)]) root.insert(i, elem) billtree=ElementTree(root) return billtree
def consultaDetalleProduccion(request, nrec): #def consultaDetalleProduccion(ncab): dajax = Dajax() nrec = DetProcesos.objects.filter(cabprocesos=CabProcesos.objects.get( pk=ncab))[0].id raiz = DetProcesos.get_root(DetProcesos.objects.get(pk=nrec)).id size = DetProcesos.get_descendant_count( DetProcesos.objects.get(id=raiz)) + 1 print raiz padre = DetProcesos.objects.get(id=raiz) cpadre = str(raiz) #Cabecera del Mensaje root = ET.Element("mxGraphModel") head = ET.SubElement(root, "root") ele = Element("mxCell") ele.set("id", "0") head.append(ele) ele1 = Element("mxCell") ele1.set("id", cpadre) ele1.set("parent", "0") head.append(ele1) objetoProcesos(head, str(raiz + 1), str(raiz + 1), str(raiz), str(raiz), padre.descripcion) print padre.descripcion nid = raiz for ele in range(0, size - 1): obj = DetProcesos.get_children(DetProcesos.objects.get(id=nid)) if len(obj) != 0: objetoProcesos(head, str(nid + 2), str(nid + 2), cpadre, cpadre, obj.values()[0]['descripcion']) print obj.values()[0]['descripcion'] nid = obj.values()[0]['id'] nid = raiz cpadre = str(raiz + 1) for ele in range(0, size - 1): obj = DetProcesos.get_children(DetProcesos.objects.get(id=nid)) if len(obj) != 0: nid = obj.values()[0]['id'] dest = nid + 1 enlaceProceso( head, str(nid + 2), str(nid + 2), str(raiz), str(raiz), cpadre, str(dest), TiposProcesos.objects.get(id=obj.values()[0]['tproceso_id'])) cpadre = str(dest) valores = simplejson.dumps(ET.tostring(root), cls=JSONEncoder) #tree = ET.ElementTree(root) #tree.write("salida.xml") return valores
def __call__ (self) : self.processed = {} self.pending = {} tree = Element ("project", id = "SW-Tasks") SubElement (tree, "label").text = ("Task(s) %s." % self.toplevel) SubElement (tree, "import-resources", file = "workers.xml") if self.VERBOSE > 1 : self.debug ("Writing `part_of` tree ...") for issue_id in self.toplevel : if self.VERBOSE > 2 : self.debug \ ("Issue %d is top-level. Processing it now ..." % issue_id) issue = self.db.issue.getnode (issue_id) self.process_issue (issue, tree) if self.VERBOSE > 1 : self.debug ("\nWriting issues due to `depends_on` or `needs` ...") while self.pending : (issue_id, issue) = self.pending.popitem () if issue_id not in self.processed : if self.VERBOSE > 2 : self.debug ("Adding %s ... " % issue_id) self.process_issue (issue, tree) else : if self.VERBOSE > 3 : self.debug ("%s already included." % issue_id) file = open (self.oname, "w") ElementTree (tree).write (file, encoding = "utf-8") if self.VERBOSE > 1 : self.debug ("Done.")
def toXML(self): # <window> window = Element('window', id=str(WINDOW_ID)) if True: # Fade in for 1.0 second (but not in screensaver mode) if not self.screensaverMode: SubElement(window, 'animation', effect='fade', time=str(1000)).text = 'WindowOpen' # <controls> controls = SubElement(window, 'controls') if True: # <control type="image"> color = Image(1280, 720, BACKGROUND_IMAGE, self.theme.background) controls.append(color.toXML()) # </control> # <control type="image"> if self.theme.image: image = Image(self.theme.imageWidth, self.theme.imageHeight, self.theme.image) else: # Placeholder for if we change the theme by pressing T image = Image(1280, 720, '-') controls.append(image.toXML()) # </control> #sprites = Sprites(self.layout, self.theme) #controls.append(sprites.toXML()) # <control type="panel"> matrix = Matrix(self.letters, self.layout, self.theme) controls.append(matrix.toXML()) # </control> # </controls> # </window> return window
def AdicionarUsuario(self,Aluno): """ Método que cria o usuário no jenkins, atualmente o jenkins está vinculado com o ldap do sistema ead, por mais que o usuário esteja criado no jenkins, ele não conseguirá autenticar se não estiver cadastrado no LDAP também. Para fazer o cadastro do aluno é adicionada mais uma linha do /var/lib/jenkins/config.xml dentro das tags <permission> somente com permissão de leitura. :param Aluno: Aluno é uma string somente com o email do aluno. :returns: Esse método não possui valor de retorno """ try: tree = parse("/var/lib/jenkins/config.xml") elem = tree.getroot() perm = elem.find('authorizationStrategy') busca = perm.findall("permission") for b in busca: if Aluno in b.text: log.warning("[!] Usuario Ja cadastrado no jenkins") return user = Element("permission") user.text = "hudson.model.Hudson.Read:%s"%Aluno perm.append(user) tree.write("/var/lib/jenkins/config.xml") log.info("[+] Usuario %s adicionado ao jenkins com Sucesso",Aluno) except Exception as e: log.error("[-] Erro ao adicionar usuario ao jenkins %s",e)
def write(pattern, fpath): import os from elementtree.ElementTree import Element, ElementTree root = Element('xml') toelem(pattern, root) ElementTree(root).write(fpath) os.system('tidy -xml -iqm \"%s\"' % fpath)
def toXML(self): '''Generate the xml representation of the letter matrix''' # <control type="panel"> control = Element('control', type='panel', id=str(CONTROL_PANEL)) if True: SubElement(control, 'posx').text = str(self.posx) SubElement(control, 'posy').text = str(self.posy) SubElement(control, 'width').text = str(self.width) SubElement(control, 'height').text = str(self.height) SubElement(control, 'onleft').text = '-' SubElement(control, 'onright').text = '-' SubElement(control, 'onup').text = '-' SubElement(control, 'ondown').text = '-' SubElement(control, 'viewtype', label='').text = 'panel' SubElement(control, 'pagecontrol').text = '-' SubElement(control, 'scrolltime').text = '-' SubElement(control, 'hitrect', x=str(-10), y=str(-10), w=str(1), h=str(1)) # <itemlayout> itemlayout = SubElement(control, 'itemlayout', height=str(self.letterHeight), width=str(self.letterWidth)) if True: self.addItemLayout(itemlayout, self.theme.inactive, 1) self.addItemLayout(itemlayout, self.theme.active, 2) # </itemlayout> SubElement(control, 'focusedlayout', height=str(self.height), width=str(self.width)) # <content> content = SubElement(control, 'content') if True: # <item> for letter in self.letters: content.append(letter.toXML()) # </item> # </content> # </control> return control
def get_runtime_inputs(self): label = self.state.get("name", "Input Dataset") return dict(input=DataToolParameter( None, Element( "param", name="input", label=label, type="data", format="data")))
def dump(self, output): tempo = {} root = Element('resources') root.tail = '\n' tempo[()] = root for key in self._resources_order: for i in range(1, len(key) + 1): if key[0:i] not in tempo: parent = tempo[key[0:i - 1]] value = self._resources.get(key[0:i], None) if value is None: elem = SubElement(parent, 'node', name=key[i - 1]) else: fullKey = key[0] for j in range(1, i): fullKey += '/' + key[j] newValue = self._dictionary[fullKey] elem = SubElement(parent, 'node', name=key[i - 1], value=newValue) parent.text = elem.tail = '\n' + i * SPACES tempo[key[0:i]] = elem fix_it(root) print >> output, '<?xml version="1.0" encoding="UTF-8"?>' ElementTree(root).write(output, 'ascii')
def build_request_xml(self, data, root_tag): root = Element(root_tag, USERID=self.user_id) for i, address in enumerate(data): address_element = SubElement(root, 'Address', ID=str(i)) for field in self.address_fields: SubElement( address_element, field).text = address.get(field.lower()) return tostring(root)
def create_node(tag, property_map, content): '''新造一个节点 tag:节点标签 property_map:属性及属性值map content: 节点闭合标签里的文本内容 return 新节点''' element = Element(tag, property_map) element.text = content return element
def get_runtime_inputs(self, filter_set=['data']): label = self.state.get("name", "Input Dataset") return dict(input=DataToolParameter( None, Element("param", name="input", label=label, multiple=True, type="data", format=', '.join(filter_set)), self.trans))
def __call__(self): s = Element("settings") f = Element("filters") f.text = self.context.extra_filters s.append(f) p = Element("verp_prefix") p.text = self.context.verp_prefix s.append(p) e_ns = Element("newsletters") for nl in self.context.objectValues("Newsletter"): n = Element("newsletter") n.text = nl.id e_ns.append(n) s.append(e_ns) return tostring(s, 'utf-8')
def get_runtime_inputs(self, filter_set=['data']): label = self.state.get("name", self.default_name) collection_type = self.state.get("collection_type", self.default_collection_type) input_element = Element("param", name="input", label=label, type="data_collection", collection_type=collection_type) return dict( input=DataCollectionToolParameter(None, input_element, self.trans))
def ConvertDialogToElement(dialog): # build a tree structure root = Element("DIALOG") for ctrl in dialog.AllControls(): ctrlElem = SubElement(root, "CONTROL") for name, value in ctrl.properties.items(): AddElement(ctrlElem, name, value) return root
def getCommand(args): result = getInterfaceInfo(args.macaddress) if result is None: print 'adapter not found' return 3 top_node = Element('NetConfigurations') formatNetworkAdapterConfig(top_node, result) print tostring(top_node) return 0
def toXML(self): '''Generate the xml representation of this Letter''' # <item> item = Element('item') if True: # <label>$INFO[Window(Home).Property(Unqlocked.0.Background)]</label> SubElement(item, 'label').text = '$INFO[Window(Home).Property(%s)]' % (PROPERTY_INACTIVE % self.index) # <label2>$INFO[Window(Home).Property(Unqlocked.0.Highlight)]</label2> SubElement(item, 'label2').text = '$INFO[Window(Home).Property(%s)]' % (PROPERTY_ACTIVE % self.index) # <onclick>-</onclick> SubElement(item, 'onclick').text = '-' # </item> return item
def gencix(major, minor): # First generate first pass at the CILE over all of the lib tree cixfile = "activeperl-%d.%d.cix" % (major, minor) command = "python ../../../ci2.py scan -n -r -p -l Perl -T /tmp/ActivePerl-%d.%d/perl/lib -i \"*.pm\"> %s" % ( major, minor, cixfile) retval = os.system(command) if retval != 0: print "Error scanning ActivePerl library" sys.exit(retval) # # Grab the output of that scan root = parse(cixfile).getroot() newroot = Element("codeintel", version="2.0") cixfile = SubElement(newroot, "file", lang="Perl", mtime=str(int(time.time())), path=os.path.basename('perl.cix')) for file in root.getiterator('file'): print >> sys.stderr, "Processing", file.get('path') for blob in file: if blob.get("src"): # Don't want the src string. del blob.attrib["src"] cixfile.append(blob) cix = genPerlStdCIX( cixfile, "/tmp/ActivePerl-%d.%d/perl/lib/pod/perlfunc.pod" % (major, minor)) parent_map = dict((c, p) for p in cixfile.getiterator() for c in p) for variable in newroot.getiterator('variable'): attributes = variable.get('attributes') if attributes and '__local__' in variable.get('attributes'): parent_map[variable].remove(variable) # Generate the CIX. print >> sys.stderr, "Prettying" prettify(newroot) tree = ElementTree(newroot) #fname = '../../../lib/codeintel2/stdlibs/perl-%d.%d.cix' % (major, minor) fname = 'perl-%d.%d.cix' % (major, minor) #os.system('p4 edit %s' % fname) stream = open(fname, "w") print >> sys.stderr, "Writing" stream.write('<?xml version="1.0" encoding="UTF-8"?>\n') tree.write(stream) stream.close()
def toXML(self): # <control> control = Element('control', type='image', id=str(self.id)) if True: SubElement(control, 'posx').text = str((1280 - self.width) / 2) SubElement(control, 'posy').text = str((720 - self.height) / 2) SubElement(control, 'width').text = str(self.width) SubElement(control, 'height').text = str(self.height) SubElement(control, 'texture').text = self.image if self.diffuse: SubElement(control, 'colordiffuse').text = self.diffuse # AARRGGBB # </control> return control
def dump(self, output, lang): tempo = {} root = Element('resources') root.tail = '\n' tempo[()] = root for key in self._resources_order: for i in range(1, len(key) + 1): if key[0:i] not in tempo: parent = tempo[key[0:i - 1]] value = self._resources.get(key[0:i], None) if value is None: elem = SubElement(parent, 'node', name=key[i - 1]) else: localized = value.get(lang, None) english = value.get('en', None) if english is None: print >> sys.stderr, 'English file does not have the string for', key[ 0:i] print >> sys.stderr, ' entry is marked as obosolete.' elem = SubElement(parent, 'node', name=key[i - 1], value=localized, obsolete='true') elif localized is not None: elem = SubElement(parent, 'node', name=key[i - 1], value=localized) else: elem = SubElement(parent, 'node', name=key[i - 1], value=english, toBeTranslated='true') parent.text = elem.tail = '\n' + i * SPACES tempo[key[0:i]] = elem fix_it(root) print >> output, '<?xml version="1.0" encoding="UTF-8"?>' ElementTree(root).write(output, 'utf-8')
def enlaceProceso(head, id, customid, edge, parent, source, target, texto): subhead = ET.SubElement(head, "mxCell") subhead.set("id", "edge-" + id) subhead.set("customId", "edge-" + customid) subhead.set("value", '<img src="editors/images/overlays/check.png"> %s' % texto) subhead.set("edge", edge) subhead.set("parent", parent) subhead.set("source", source) subhead.set("target", target) subele = Element("mxGeometry") subele.set("relative", "1") subele.set("as", "geometry") subhead.append(subele)
def _format(self, elemap, obj): defaults = self._defaults out = Element(elemap[0]) for subspec in elemap[1:]: if type(subspec) == type(''): tmp = obj.get(subspec, None) if tmp is None or str(tmp) == '': tmp = defaults.get(subspec, '') out.text = str(tmp) continue # here, subspec is really a recursive element map subelem = self._format(subspec, obj) out.append(subelem) return out
def listCommand(args): if isWindows(): result = [win32GetInterfaceInfo(i) for i in win32EnumerateInterfaces()] elif isLinux() or isBsd(): result = unixGetInterfaceList() else: raise Exception('Unsupported operating system') top_node = Element('NetConfigurations') for adapter in result: formatNetworkAdapterConfig(top_node, adapter) print tostring(top_node) return 0
def createFilePodcast(mediaFilePath, title, description=''): """ create the xml file using utf """ mediaItem = Element("media") mediaItem.attrib["version"] = VERSION titleNode = SubElement(mediaItem, "title") titleNode.text = title descrNode = SubElement(mediaItem, "description") descrNode.text = description createXmlFile(mediaFilePath + '.xml', mediaItem) mediaItem.clear()
def writePolygon(self, objGeo, elemPlace): elemGeo = Element('Polygon') #Now add the ring(s) dctRings = objGeo.getRingInfo() #get the external ring(s) lstOuter = objGeo.getRing('Outer') lstInner = objGeo.getRing('Inner') for x in range(0, dctRings['Outer']): elemRing = self.addRing(lstOuter[x], 'Outer') elemGeo.append(elemRing) for x in range(0, dctRings['Inner']): elemRing = self.addRing(lstInner[x], 'Inner') elemGeo.append(elemRing) return elemGeo