我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用xml.etree.ElementTree.SubElement()。
def formatAlertsCount(numberofalerts, outformat): """ Create XML / Json Structure with number of Alerts in requested timespan """ if outformat == "xml": ewssimpleinfo = ET.Element('EWSSimpleIPInfo') alertCount = ET.SubElement(ewssimpleinfo, 'AlertCount') if numberofalerts: alertCount.text = str(numberofalerts) else: alertCount.text = str(0) prettify(ewssimpleinfo) alertcountxml = '<?xml version="1.0" encoding="UTF-8"?>' alertcountxml += (ET.tostring(ewssimpleinfo, encoding="utf-8", method="xml")).decode('utf-8') return alertcountxml else: return ({'AlertCount': numberofalerts})
def _set_boot_device(conn, domain, device): """Set the boot device. :param conn: active libvirt connection. :param domain: libvirt domain object. :raises: LibvirtError if failed update domain xml. """ parsed = ET.fromstring(domain.XMLDesc()) os = parsed.find('os') boot_list = os.findall('boot') # Clear boot list for boot_el in boot_list: os.remove(boot_el) boot_el = ET.SubElement(os, 'boot') boot_el.set('dev', device) try: conn.defineXML(ET.tostring(parsed)) except libvirt.libvirtError as e: raise isd_exc.LibvirtError(err=e)
def exportXML(self): elements = list() for node in anytree.PreOrderIter(self.tree): nodeName = parameters.encodeXMLName(node.name) if not elements: top = xmlElement(self.tree.name) top.attrib['name'] = self.tree.name top.attrib['is_checked'] = 'False' top.attrib['is_default'] = 'False' elements.append(top) continue for e in elements: if e.attrib['name'] == node.parent.name: se = xmlSubElement(e, nodeName) se.attrib['name'] = node.name se.attrib['is_checked'] = 'True' if node.is_checked else 'False' se.attrib['is_default'] = 'True' if node.is_default else 'False' se.attrib['parent'] = e.attrib['name'] elements.append(se) break # else: # print('could not find parent for {}'.format(node.name)) string = xmlElementTree.tostring(top, encoding='unicode', method='xml') return string
def to_xml(self): """Produces an XML out of the point data. Disregards the "action" field.""" el = etree.Element(self.osm_type, id=str(self.osm_id), version=str(self.version)) for tag, value in self.tags.items(): etree.SubElement(el, 'tag', k=tag, v=value) if self.osm_type == 'node': el.set('lat', str(self.lat)) el.set('lon', str(self.lon)) elif self.osm_type == 'way': for node_id in self.members: etree.SubElement(el, 'nd', ref=str(node_id)) elif self.osm_type == 'relation': for member in self.members: m = etree.SubElement(el, 'member') for i, n in enumerate(('type', 'ref', 'role')): m.set(n, str(member[i])) return el
def gen_xml(self, xml_parent, data): definition = data.get(self.component_type, {}) scm_definition = 'scm' in definition definition_type = 'CpsScmFlowDefinition' if scm_definition else 'CpsFlowDefinition' xml_definition = XML.SubElement( xml_parent, 'definition', { 'plugin': 'workflow-cps', 'class': 'org.jenkinsci.plugins.workflow.cps.' + definition_type } ) if scm_definition: scm_module = next(module for module in self.registry.modules if isinstance(module, SCM)) scm_module.gen_xml(xml_definition, definition) XML.SubElement(xml_definition, 'scriptPath').text = definition.get('script-path', 'Jenkinsfile') else: XML.SubElement(xml_definition, 'script').text = definition.get('script', '') XML.SubElement(xml_definition, 'sandbox').text = str(definition.get('sandbox', False)).lower()
def generate_xml(self, parent): """ Generates the XML element for this node. :param xml.etree.ElementTree.Element parent: The parent XML element. """ command_job = SubElement(parent, 'CommandJob') self._generate_xml_common(command_job) path = SubElement(command_job, 'Path') path.text = self.path if self.args: args_element = SubElement(command_job, 'Args') for arg in self.args: argument = SubElement(args_element, 'Arg') argument.text = str(arg) # ------------------------------------------------------------------------------------------------------------------
def UrhoWriteTriggers(triggersList, filename, fOptions): triggersElem = ET.Element('animation') for trigger in triggersList: triggerElem = ET.SubElement(triggersElem, "trigger") if trigger.time is not None: triggerElem.set("time", FloatToString(trigger.time)) if trigger.ratio is not None: triggerElem.set("normalizedtime", FloatToString(trigger.ratio)) # We use a string variant, for other types See typeNames[] in Variant.cpp # and XMLElement::GetVariant() triggerElem.set("type", "String") triggerElem.set("value", str(trigger.data)) WriteXmlFile(triggersElem, filename, fOptions) #-------------------- # Utils #-------------------- # Search for the most complete element mask
def export(self, filename): self.nodes, self.renderer = self.compute() initWidth, initHeight = (self.options['initialWidth'], self.options['initialHeight']) doc = ElementTree.Element('svg', width=str(initWidth), height=str(initHeight)) transform = self.getTranslation() trans = ElementTree.SubElement(doc, 'g', transform=transform) ElementTree.SubElement(trans, 'g', attrib={'class': 'dummy-layer'}) mainLayer = self.add_main(trans) self.add_timeline(mainLayer) if self.options['showTicks']: self.add_axis(mainLayer) self.add_links(mainLayer) self.add_labels(mainLayer) self.add_dots(mainLayer) svglines = ElementTree.tostring(doc) with open(filename, 'wb') as fid: fid.write(svglines) return svglines
def writeXML(dataObj, fname, dtdPath): if dataObj.predSev == 0: sev = "ABSENT" elif dataObj.predSev == 1: sev = "MILD" elif dataObj.predSev == 2: sev = "MODERATE" elif dataObj.predSev == 3: sev = "SEVERE" root = ET.Element("RDoC") ET.SubElement(root, "TEXT").text = dataObj.text.content tags = ET.SubElement(root, "TAGS") pos_val = ET.SubElement(tags, "POSITIVE_VALENCE") pos_val.set('score', sev) pos_val.set('annotated_by', dataObj.Nannotators) tree = ET.ElementTree(root) tree.write(fname)
def pSuite_testcase(resultfile, classname, name, time): global currentTestSuitePointer global currentTestCasePointer global gTestSuite global gTestSuiteLoop global gTestCase global gTestCaseLoop gTestCase[gTestCaseLoop] = ET.SubElement(currentTestSuitePointer,"testcase") gTestCase[gTestCaseLoop].set('classname',classname) gTestCase[gTestCaseLoop].set('name',name) gTestCase[gTestCaseLoop].set('time',time) currentTestCasePointer = gTestCase[gTestCaseLoop] printOutput()
def convert_tddict_to_xmlobj(self, root, tddict): """ To Convert the testdata dictionary into a xml object. Testdata dictionary can have following combinations : 1. dict within dict 2. list within dict 3. dict within list """ for element in tddict: if isinstance(tddict[element], dict): self.convert_tddict_to_xmlobj(ET.SubElement(root, element), tddict[element]) elif isinstance(tddict[element], list): for list_elem in tddict[element]: # here list can only have dictionary in it if isinstance(list_elem, dict): self.convert_tddict_to_xmlobj(ET.SubElement(root, element), list_elem) else: root.set(element, tddict[element])
def setInterfaceBandwidth(self,instance,port,bandwidth): '''????''' domXml = instance.XMLDesc(0) root = ElementTree.fromstring(domXml) try: for dev in root.findall('.//devices/'): if dev.tag == 'interface': for iter in dev: if iter.tag == 'target' and iter.get('dev') == port: bwXml = ElementTree.SubElement(dev,'bandwidth') inbdXml = ElementTree.Element('inbound') inbdXml.set('average',str(int(bandwidth)*1024)) inbdXml.set('peak',str(int(bandwidth)*1024)) inbdXml.set('burst','1024') outbdXml = ElementTree.Element('outbound') outbdXml.set('average',str(int(bandwidth)*1024)) outbdXml.set('peak',str(int(bandwidth)*1024)) outbdXml.set('burst','1024') bwXml.append(inbdXml) bwXml.append(outbdXml) domXml = ElementTree.tostring(root) except Exception,e: return {"status":"faild",'data':e} if self.defineXML(domXml):return {"status":"success",'data':None}
def attach_page_style(self, el): """Attach the default page style. Create an automatic-style that refers to the current style of this element and that refers to the default page style. """ current_style = el.get('text:style-name') style_name = 'P1003' el1 = SubElement( self.automatic_styles, 'style:style', attrib={ 'style:name': style_name, 'style:master-page-name': "rststyle-pagedefault", 'style:family': "paragraph", }, nsdict=SNSD) if current_style: el1.set('style:parent-style-name', current_style) el.set('text:style-name', style_name)
def visit_enumerated_list(self, node): el1 = self.current_element if self.blockstyle == self.rststyle('blockquote'): el2 = SubElement(el1, 'text:list', attrib={ 'text:style-name': self.rststyle('blockquote-enumlist'), }) self.list_style_stack.append(self.rststyle('blockquote-enumitem')) elif self.blockstyle == self.rststyle('highlights'): el2 = SubElement(el1, 'text:list', attrib={ 'text:style-name': self.rststyle('highlights-enumlist'), }) self.list_style_stack.append(self.rststyle('highlights-enumitem')) elif self.blockstyle == self.rststyle('epigraph'): el2 = SubElement(el1, 'text:list', attrib={ 'text:style-name': self.rststyle('epigraph-enumlist'), }) self.list_style_stack.append(self.rststyle('epigraph-enumitem')) else: liststylename = 'enumlist-%s' % (node.get('enumtype', 'arabic'), ) el2 = SubElement(el1, 'text:list', attrib={ 'text:style-name': self.rststyle(liststylename), }) self.list_style_stack.append(self.rststyle('enumitem')) self.set_current_element(el2)
def visit_inline(self, node): styles = node.attributes.get('classes', ()) if styles: el = self.current_element for inline_style in styles: el = SubElement(el, 'text:span', attrib={'text:style-name': self.rststyle(inline_style)}) count = len(styles) else: # No style was specified so use a default style (old code # crashed if no style was given) el = SubElement(self.current_element, 'text:span') count = 1 self.set_current_element(el) self.inline_style_count_stack.append(count)
def visit_colspec(self, node): self.column_count += 1 colspec_name = self.rststyle( '%s%%d.%%s' % TABLESTYLEPREFIX, (self.table_count, chr(self.column_count), ) ) colwidth = node['colwidth'] / 12.0 el1 = SubElement(self.automatic_styles, 'style:style', attrib={ 'style:name': colspec_name, 'style:family': 'table-column', }, nsdict=SNSD) el1_1 = SubElement(el1, 'style:table-column-properties', attrib={ 'style:column-width': '%.4fin' % colwidth }, nsdict=SNSD) el2 = self.append_child('table:table-column', attrib={ 'table:style-name': colspec_name, }) self.table_width += colwidth
def _serialize_type_structure(self, xmlnode, params, shape, name): structure_node = ElementTree.SubElement(xmlnode, name) if 'xmlNamespace' in shape.serialization: namespace_metadata = shape.serialization['xmlNamespace'] attribute_name = 'xmlns' if namespace_metadata.get('prefix'): attribute_name += ':%s' % namespace_metadata['prefix'] structure_node.attrib[attribute_name] = namespace_metadata['uri'] for key, value in params.items(): member_shape = shape.members[key] member_name = member_shape.serialization.get('name', key) # We need to special case member shapes that are marked as an # xmlAttribute. Rather than serializing into an XML child node, # we instead serialize the shape to an XML attribute of the # *current* node. if value is None: # Don't serialize any param whose value is None. return if member_shape.serialization.get('xmlAttribute'): # xmlAttributes must have a serialization name. xml_attribute_name = member_shape.serialization['name'] structure_node.attrib[xml_attribute_name] = value continue self._serialize(member_shape, value, structure_node, member_name)
def _serialize_type_map(self, xmlnode, params, shape, name): # Given the ``name`` of MyMap, and input of {"key1": "val1"} # we serialize this as: # <MyMap> # <entry> # <key>key1</key> # <value>val1</value> # </entry> # </MyMap> node = ElementTree.SubElement(xmlnode, name) # TODO: handle flattened maps. for key, value in params.items(): entry_node = ElementTree.SubElement(node, 'entry') key_name = self._get_serialized_name(shape.key, default_name='key') val_name = self._get_serialized_name(shape.value, default_name='value') self._serialize(shape.key, key, entry_node, key_name) self._serialize(shape.value, value, entry_node, val_name)
def create_xml_page(dictionary: dict, creator_name='DocSeg') -> 'Page': page = Page.from_dict(dictionary) # Create xml root = ET.Element('PcGts') root.set('xmlns', _ns['p']) # Metadata generated_on = str(datetime.datetime.now()) metadata = ET.SubElement(root, 'Metadata') creator = ET.SubElement(metadata, 'Creator') creator.text = creator_name created = ET.SubElement(metadata, 'Created') created.text = generated_on last_change = ET.SubElement(metadata, 'LastChange') last_change.text = generated_on root.append(page.to_xml()) for k, v in _attribs.items(): root.attrib[k] = v return root
def generate_admonition(self, node, label, title=None): if hasattr(self.language, 'labels'): translated_label = self.language.labels[label] else: translated_label = label el1 = SubElement(self.current_element, 'text:p', attrib={ 'text:style-name': self.rststyle( 'admon-%s-hdr', (label, )), }) if title: el1.text = title else: el1.text = '%s!' % (translated_label.capitalize(), ) s1 = self.rststyle('admon-%s-body', (label, )) self.paragraph_style_stack.append(s1) # # Roles (e.g. subscript, superscript, strong, ... #
def addPoint(tree,point,pointtype='c'): """Draw a point on the XML tree. A function for testing. Args: tree (obj): An XML tree. newpath (obj): The path to be added. pointtype (str): The string of point type. """ x_str,y_str = str(point[0]),str(point[1]) root = tree.getroot() for pointaddr in root.iter('{http://www.w3.org/2000/svg}g'): point = ET.SubElement(pointaddr,'{http://www.w3.org/2000/svg}circle') # Offer two colour choice if pointtype == 'c': point.attrib['style'] = 'fill: #0000ff' else: point.attrib['style'] = 'fill: #FF0000' point.attrib['cx'] = x_str point.attrib['cy'] = y_str point.attrib['r'] = '0.5' point.tail = '\n'
def onFinishBuilding(app, exception): currentVersion = app.env.config["version"] if "latest_docs_version" in app.env.config["html_context"].keys(): latestVersion = app.env.config["html_context"]["latest_docs_version"] else: latestVersion = "dev" base_domain = app.env.config["html_context"]["SITEMAP_DOMAIN"] file_path = "./_build/algolia_index/index.json" sitemap_path = "./_build/sitemap/sitemap_" + currentVersion + ".xml" checkDirectory(file_path) checkDirectory(sitemap_path) f = open(file_path, 'w+') root = ET.Element("urlset") root.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9") for link in indexObjs: url = ET.SubElement(root, "url") ET.SubElement(url, "loc").text = base_domain + str(currentVersion) + "/" + link["url"] ET.SubElement(url, "changefreq").text = "daily" ET.SubElement(url, "priority").text = "1" if ( currentVersion == latestVersion ) else "0.5" ET.ElementTree(root).write(sitemap_path) f.write(json.dumps(indexObjs))
def eccu_doc_for_purge_dir(path_to_purge): root = ET.Element('eccu') parent = root names = (name for name in path_to_purge.split('/') if name) for name in names: parent = ET.SubElement(parent, 'match:recursive-dirs', {'value': name}) revalidate = ET.SubElement(parent, 'revalidate') revalidate.text = 'now' return ET.tostring(root, encoding='ascii') #'<?xml version="1.0"?>\n' + ET.tostring(root) #xml = StringIO() #xml.write('<?xml version="1.0"?>\n') #xml.write(ET.tostring(root)) #return xml
def add_to_document(self, parent): """Adds an ``Argument`` object to this ElementTree document. Adds an <arg> subelement to the parent element, typically <args> and sets up its subelements with their respective text. :param parent: An ``ET.Element`` to be the parent of a new <arg> subelement :returns: An ``ET.Element`` object representing this argument. """ arg = ET.SubElement(parent, "arg") arg.set("name", self.name) if self.title is not None: ET.SubElement(arg, "title").text = self.title if self.description is not None: ET.SubElement(arg, "description").text = self.description if self.validation is not None: ET.SubElement(arg, "validation").text = self.validation # add all other subelements to this Argument, represented by (tag, text) subelements = [ ("data_type", self.data_type), ("required_on_edit", self.required_on_edit), ("required_on_create", self.required_on_create) ] for name, value in subelements: ET.SubElement(arg, name).text = str(value).lower() return arg
def to_xml(self): """Creates an ``ET.Element`` representing self, then returns it. :returns root, an ``ET.Element`` representing this scheme. """ root = ET.Element("scheme") ET.SubElement(root, "title").text = self.title # add a description subelement if it's defined if self.description is not None: ET.SubElement(root, "description").text = self.description # add all other subelements to this Scheme, represented by (tag, text) subelements = [ ("use_external_validation", self.use_external_validation), ("use_single_instance", self.use_single_instance), ("streaming_mode", self.streaming_mode) ] for name, value in subelements: ET.SubElement(root, name).text = str(value).lower() endpoint = ET.SubElement(root, "endpoint") args = ET.SubElement(endpoint, "args") # add arguments as subelements to the <args> element for arg in self.arguments: arg.add_to_document(args) return root
def write_to(self, stream): """Write an XML representation of self, an ``Event`` object, to the given stream. The ``Event`` object will only be written if its data field is defined, otherwise a ``ValueError`` is raised. :param stream: stream to write XML to. """ if self.data is None: raise ValueError("Events must have at least the data field set to be written to XML.") event = ET.Element("event") if self.stanza is not None: event.set("stanza", self.stanza) event.set("unbroken", str(int(self.unbroken))) # if a time isn't set, let Splunk guess by not creating a <time> element if self.time is not None: ET.SubElement(event, "time").text = str(self.time) # add all other subelements to this Event, represented by (tag, text) subelements = [ ("source", self.source), ("sourcetype", self.sourceType), ("index", self.index), ("host", self.host), ("data", self.data) ] for node, value in subelements: if value is not None: ET.SubElement(event, node).text = value if self.done: ET.SubElement(event, "done") stream.write(ET.tostring(event)) stream.flush()
def set_boot_device(self, bootdevice): LOG.debug('Set boot device called for %(domain)s with boot ' 'device "%(bootdev)s"', {'domain': self.domain_name, 'bootdev': bootdevice}) device = SET_BOOT_DEVICES_MAP.get(bootdevice) if device is None: return 0xd5 with utils.libvirt_open(**self._conn_args) as conn: domain = utils.get_libvirt_domain(conn, self.domain_name) tree = ET.fromstring(domain.XMLDesc()) for os_element in tree.findall('os'): # Remove all "boot" elements for boot_element in os_element.findall('boot'): os_element.remove(boot_element) # Add a new boot element with the request boot device boot_element = ET.SubElement(os_element, 'boot') boot_element.set('dev', device) try: conn.defineXML(ET.tostring(tree)) except libvirt.libvirtError as e: LOG.error('Failed setting the boot device %(bootdev)s for ' 'domain %(domain)s', {'bootdev': device, 'domain': self.domain_name})
def __walk(self, node, parent): name = self.__genName(node.tag) tag = self.__getNamespace(node.tag) if parent is None: self.root = name self.lines.append("%s = ET.Element(%s)" % (name, tag)) else: self.lines.append("%s = ET.SubElement(%s, %s)" % (name, parent, tag)) # handles text try: t = node.text.strip() if t == '': t = None except: t = None if t is not None: self.lines.append("%s.text = kwargs.get('', '%s') # PARAMETERIZE" % (name, t)) # handles attributes for key,val in node.items(): key = self.__getNamespace(key) self.lines.append("%s.set(%s, kwargs.get('', '%s')) # PARAMETERIZE" % (name, key, val)) for i in node.getchildren(): self.__walk(i, name)
def _save_xml_report(self, s): '''use cppcheck xml result string, add the command string used to invoke cppcheck and save as xml file. ''' header = '%s\n' % s.splitlines()[0] root = ElementTree.fromstring(s) cmd = ElementTree.SubElement(root.find('cppcheck'), 'cmd') cmd.text = str(self.cmd) body = ElementTree.tostring(root) node = self.generator.path.get_bld().find_or_declare('cppcheck.xml') node.write(header + body)
def export_orders(self): for order in self.item_processor.yield_item(Order): order_element = ET.SubElement(self.root, u'????????') ET.SubElement(order_element, u'??').text = six.text_type(order.id) ET.SubElement(order_element, u'?????').text = six.text_type(order.number) ET.SubElement(order_element, u'????').text = six.text_type(order.date.strftime('%Y-%m-%d')) ET.SubElement(order_element, u'?????').text = six.text_type(order.time.strftime('%H:%M:%S')) ET.SubElement(order_element, u'???????????').text = six.text_type(order.operation) ET.SubElement(order_element, u'????').text = six.text_type(order.role) ET.SubElement(order_element, u'??????').text = six.text_type(order.currency_name) ET.SubElement(order_element, u'????').text = six.text_type(order.currency_rate) ET.SubElement(order_element, u'?????').text = six.text_type(order.sum) ET.SubElement(order_element, u'???????????').text = six.text_type(order.comment) clients_element = ET.SubElement(order_element, u'???????????') client_element = ET.SubElement(clients_element, u'??????????') ET.SubElement(client_element, u'??').text = six.text_type(order.client.id) ET.SubElement(client_element, u'????????????').text = six.text_type(order.client.name) ET.SubElement(client_element, u'????').text = six.text_type(order.client.role) ET.SubElement(client_element, u'??????????????????').text = six.text_type(order.client.full_name) ET.SubElement(client_element, u'???????').text = six.text_type(order.client.last_name) ET.SubElement(client_element, u'???').text = six.text_type(order.client.first_name) address_element = ET.SubElement(clients_element, u'????????????????') ET.SubElement(clients_element, u'?????????????').text = six.text_type(order.client.address) products_element = ET.SubElement(order_element, u'??????') for order_item in order.items: product_element = ET.SubElement(products_element, u'?????') ET.SubElement(product_element, u'??').text = six.text_type(order_item.id) ET.SubElement(product_element, u'????????????').text = six.text_type(order_item.name) sku_element = ET.SubElement(product_element, u'?????????????? ') sku_element.set(u'???', order_item.sku.id) sku_element.set(u'??????????????????', order_item.sku.name_full) sku_element.set(u'???????????????????????', order_item.sku.international_abbr) sku_element.text = order_item.sku.name ET.SubElement(product_element, u'?????????????').text = six.text_type(order_item.price) ET.SubElement(product_element, u'??????????').text = six.text_type(order_item.quant) ET.SubElement(product_element, u'?????').text = six.text_type(order_item.sum)
def backup_osm(self): """Writes OSM data as-is.""" osm = etree.Element('osm', version='0.6', generator=TITLE) for osmel in self.osmdata.values(): el = osmel.to_xml() if osmel.osm_type != 'node': etree.SubElement(el, 'center', lat=str(osmel.lat), lon=str(osmel.lon)) osm.append(el) return ("<?xml version='1.0' encoding='utf-8'?>\n" + etree.tostring(osm, encoding='utf-8').decode('utf-8'))
def to_osc(self, josm=False): """Returns a string with osmChange or JOSM XML.""" osc = etree.Element('osm' if josm else 'osmChange', version='0.6', generator=TITLE) if josm: neg_id = -1 changeset = etree.SubElement(osc, 'changeset') ch_tags = { 'source': self.source, 'created_by': TITLE, 'type': 'import' } for k, v in ch_tags.items(): etree.SubElement(changeset, 'tag', k=k, v=v) for osmel in self.matched: if osmel.action is not None: el = osmel.to_xml() if josm: if osmel.action == 'create': el.set('id', str(neg_id)) neg_id -= 1 else: el.set('action', osmel.action) osc.append(el) else: etree.SubElement(osc, osmel.action).append(el) return ("<?xml version='1.0' encoding='utf-8'?>\n" + etree.tostring(osc, encoding='utf-8').decode('utf-8'))
def saveTree(self,store): """ @description: save the treeview in the mama.xml file @param: store the listStore attach to the treeview """ # if there is still an entry in the model config = expanduser('~') +'/.config/mama/mama.xml' try: if not os.path.exists(os.path.dirname(config)): os.makedirs(os.path.dirname(config)) root = ET.Element("data") if len(store) != 0: for i in range(len(store)): iter = store.get_iter(i) if store[iter][0] != '' and store[iter][1] != '': for s in store[iter][0].split('|'): s = s.lower() s = s.replace('*',' ') Type = ET.SubElement(root, "entry") Type.set("name",unicode(store[iter][2],"utf-8")) Key = ET.SubElement(Type, "key") Key.text = unicode(s,"utf-8") Command = ET.SubElement(Type, "command") Command.text = unicode(store[iter][1],"utf-8") Linker = ET.SubElement(Type, "linker") Spacebyplus = ET.SubElement(Type, "spacebyplus") if store[iter][3] is not None or store[iter][4] is not None: Linker.text = unicode(store[iter][3],"utf-8") Spacebyplus.text = unicode(store[iter][4],"utf-8") tree = ET.ElementTree(root).write(config,encoding="utf-8",xml_declaration=True) except IOError: print("Unable to write the file")
def saveTree(self, store): """ @description: save the treeview in the mama.xml file @param: store the listStore attach to the treeview """ # if there is still an entry in the model config = expanduser('~') + '/.config/mama/mama.xml' try: if not os.path.exists(os.path.dirname(config)): os.makedirs(os.path.dirname(config)) root = ET.Element("data") if len(store) != 0: for i in range(len(store)): iter = store.get_iter(i) if store[iter][0] != '' and store[iter][1] != '': for s in store[iter][0].split('|'): s = s.lower() s = s.replace('*', ' ') Type = ET.SubElement(root, "entry") Type.set("name", unicode(store[iter][2], "utf-8")) Key = ET.SubElement(Type, "key") Key.text = unicode(s, "utf-8") Command = ET.SubElement(Type, "command") Command.text = unicode(store[iter][1], "utf-8") Linker = ET.SubElement(Type, "linker") Spacebyplus = ET.SubElement(Type, "spacebyplus") if store[iter][3] is not None and store[iter][ 4] is not None: Linker.text = unicode(store[iter][3], "utf-8") Spacebyplus.text = unicode(store[iter][4], "utf-8") tree = ET.ElementTree(root).write(config, encoding="utf-8", xml_declaration=True) except IOError: print("Unable to write the file")
def saveTree(self, store): """ @description: save the treeview in the mama.xml file @param: store the listStore attach to the treeview """ # if there is still an entry in the model config = expanduser('~') + '/.config/mama/mama.xml' try: if not os.path.exists(os.path.dirname(config)): os.makedirs(os.path.dirname(config)) root = ET.Element("data") if len(store) != 0: for i in range(len(store)): iter = store.get_iter(i) if store[iter][0] != '' and store[iter][1] != '': for s in store[iter][0].split('|'): s = s.lower() s = s.replace('*', ' ') Type = ET.SubElement(root, "entry") Type.set("name", unicode(store[iter][2], "utf-8")) Key = ET.SubElement(Type, "key") Key.text = unicode(s, "utf-8") Command = ET.SubElement(Type, "command") Command.text = unicode(store[iter][1], "utf-8") Linker = ET.SubElement(Type, "linker") Spacebyplus = ET.SubElement(Type, "spacebyplus") if store[iter][3] is not None and store[iter][ 4] is not None: Linker.text = unicode(store[iter][3], "utf-8") Spacebyplus.text = unicode(store[iter][4], "utf-8") ET.ElementTree(root).write(config, encoding="utf-8", xml_declaration=True) except IOError: print("Unable to write the file")
def _generate_xml_common(self, parent): """ Generates the common XML elements of the XML element for this :param xml.etree.ElementTree.Element parent: The parent XML element (i.e. the resource XML element). """ resource_name = SubElement(parent, 'ResourceName') resource_name.text = self.name # ----------------------------------------------------------------------------------------------------------------------
def generate_xml(self, parent): """ Generates the XML element for this resource. :param xml.etree.ElementTree.Element parent: The parent XML element. """ resource = SubElement(parent, 'CountingResource') self._generate_xml_common(resource) amount = SubElement(resource, 'Amount') amount.text = str(self.amount) # ----------------------------------------------------------------------------------------------------------------------
def generate_xml(self, parent): """ Generates the XML element for this resource. :param xml.etree.ElementTree.Element parent: The parent XML element. """ resource = SubElement(parent, 'ReadWriteLockResource') self._generate_xml_common(resource) # ----------------------------------------------------------------------------------------------------------------------