def parseResponse(self, xml): # Return value of method result_xml = pywbem.tupletree.xml_to_tupletree( tostring(xml.find('.//RETURNVALUE'))) result_tt = pywbem.tupleparse.parse_any(result_xml) result = cim_obj.tocimobj(result_tt[1]['PARAMTYPE'], result_tt[2]) # Output parameters params_xml = [ pywbem.tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall('.//PARAMVALUE') ] params_tt = [pywbem.tupleparse.parse_any(x) for x in params_xml] params = {} for p in params_tt: if p[1] == 'reference': params[p[0]] = p[2] else: params[p[0]] = cim_obj.tocimobj(p[1], p[2]) return (result, params)
def parseResponse(self, xml): # Return value of method result_xml = pywbem.tupletree.xml_to_tupletree(tostring(xml.find(".//RETURNVALUE"))) result_tt = pywbem.tupleparse.parse_any(result_xml) result = cim_obj.tocimobj(result_tt[1]["PARAMTYPE"], result_tt[2]) # Output parameters params_xml = [pywbem.tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall(".//PARAMVALUE")] params_tt = [pywbem.tupleparse.parse_any(x) for x in params_xml] params = {} for p in params_tt: if p[1] == "reference": params[p[0]] = p[2] else: params[p[0]] = cim_obj.tocimobj(p[1], p[2]) return (result, params)
def test_oauth_dict(self): from wuhanx.account import oauth_response_to_profile_dict as oauth_dict from wuhanx.account import oauth_response_to_profile as oauth_profile from elementtree import ElementTree from elementtree.ElementTree import Element, SubElement, dump, tostring parser = ElementTree.XMLParser(encoding="utf-8") xml = ElementTree.fromstring(rpx_response_xml, parser=parser) xml.find('.//email').text = '*****@*****.**' self.assertEquals(oauth_dict('rpx', tostring(xml))['email'], '*****@*****.**') xml.find('.//email').text = '' xml.find('.//verifiedEmail').text = '' self.assertEquals(oauth_dict('rpx', tostring(xml))['email'], '') xml.find('.//email').text = None self.assertEquals(oauth_dict('rpx', tostring(xml))['email'], '') rp = oauth_dict('rpx', rpx_response_xml) uuid = rp['id'] self.assertEquals(uuid, 'https://www.google.com/accounts/o8/id?id=AItOawnGrCA3hhOS3NO0YrcFEMbgwyylcrWMZBI') print rp dp = oauth_dict('douban', douban_response_xml) print dp self.assertEquals(dp['id'], 'http://api.douban.com/people/ahbei') p1 = oauth_profile('rpx', rpx_response_xml) p2 = oauth_profile('douban', douban_response_xml)
def _store_entry(self, id, entry): now = time.time() create = False if not id: create = True etree = self._parse(entry) if not id: id = self._id_from_title(etree) self._set_atom_id(etree, id) self._set_updated(etree, now) self._set_link_rel_edit(etree, id) title = self._get_title(etree) etree = self.filter.check(etree) if etree: updated_entry = etree.getiterator(ATOM_ENTRY)[0] if create: self.cur.execute( "insert into store(id, title, last_modified, created, entry) values (?, ?, ?, ?, ?)", (id, title, now, now, tostring(updated_entry, 'utf-8'))) else: self.cur.execute( "update store set title=?, last_modified=?, entry=? where id=?", (title, now, tostring(updated_entry, 'utf-8'), id)) if not create: self._clear_old_indices(id) self._add_indices(id, etree) self.con.commit() return (unicode(id), etree) else: raise AtomStoreExp("Entry failed to meet the requirements.")
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 parseResponse(self, xml): if len(xml.findall(".//INSTANCENAME")) > 0: tt = [pywbem.tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall(".//INSTANCENAME")] return [pywbem.tupleparse.parse_instancename(x) for x in tt] else: tt = [pywbem.tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall(".//OBJECTPATH")] return [pywbem.tupleparse.parse_objectpath(x)[2] for x in tt]
def parseResponse(self, xml): res = [] part_results = {} results_for_monitoring = {} for paramvalue in xml.findall('.//PARAMVALUE'): str_paramvalue = tostring(paramvalue) tuple_paramvalue = pywbem.tupletree.xml_to_tupletree( str_paramvalue) part_results.update( pywbem.tupleparse.parse_iter_paramvalue(tuple_paramvalue)) for x in xml.findall('.//VALUE.INSTANCEWITHPATH'): s = tostring(x) tt = pywbem.tupletree.xml_to_tupletree(s) part_res = pywbem.tupleparse.parse_value_instancewithpath(tt) result_element = part_res['VALUE.INSTANCEWITHPATH'] specific_prop_name, _ = self.property_filter specific_prop = False if specific_prop_name and specific_prop_name in result_element: specific_prop = result_element[specific_prop_name] if specific_prop: specific_prop_value = None component_identifier = None if specific_prop_name in result_element: specific_prop_value = str( result_element[specific_prop_name]) if self.result_component_key in result_element: component_identifier = result_element[ self.result_component_key] monitoring_result = { self.classname: { (specific_prop_name, specific_prop_value): { (self.result_component_key, component_identifier): result_element } } } extend_results(results_for_monitoring, monitoring_result) else: res.append(result_element) if results_for_monitoring: part_results.update({'IRETURNVALUE': results_for_monitoring}) else: part_results.update({'IRETURNVALUE': res}) return OpenEnumerateInstances._getResultParams(part_results)
def parseResponse(self, xml): res = [] part_results = {} results_for_monitoring = {} for paramvalue in xml.findall('.//PARAMVALUE'): str_paramvalue = tostring(paramvalue) tuple_paramvalue = pywbem.tupletree.xml_to_tupletree(str_paramvalue) part_results.update(pywbem.tupleparse.parse_iter_paramvalue(tuple_paramvalue)) for x in xml.findall('.//VALUE.INSTANCEWITHPATH'): s = tostring(x) tt = pywbem.tupletree.xml_to_tupletree(s) part_res = pywbem.tupleparse.parse_value_instancewithpath(tt) result_element = part_res['VALUE.INSTANCEWITHPATH'] specific_prop_name, _ = self.property_filter specific_prop = False if specific_prop_name and specific_prop_name in result_element: specific_prop = result_element[specific_prop_name] if specific_prop: specific_prop_value = None component_identifier = None if specific_prop_name in result_element: specific_prop_value = str(result_element[specific_prop_name]) if self.result_component_key in result_element: component_identifier = result_element[ self.result_component_key ] monitoring_result = { self.classname: { (specific_prop_name, specific_prop_value): { (self.result_component_key, component_identifier): result_element } } } extend_results(results_for_monitoring, monitoring_result) else: res.append(result_element) if results_for_monitoring: part_results.update({'IRETURNVALUE': results_for_monitoring}) else: part_results.update({'IRETURNVALUE': res}) return OpenEnumerateInstances._getResultParams(part_results)
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 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 main(): top_node = Element('osinfo') if sys.platform == 'win32': info = windowsInfo() elif sys.platform == 'linux2': info = linuxInfo() elif sys.platform.startswith('freebsd'): info = bsdInfo() SubElement(top_node, 'name').text = info['name'] SubElement(top_node, 'version').text = info['version'] SubElement(top_node, 'details').text = info['details'] print tostring(top_node) return 0
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 process_rss_feed(request, link_id_encoded, website_encode_id): from atrinsic.base.models import Link, Website from atrinsic.web.helpers import base36_decode from elementtree.ElementTree import XML, tostring import urllib2 link = Link.objects.get(pk=base36_decode(link_id_encoded)) website = Website.objects.get(pk=base36_decode(website_encode_id)) tracking_url = link.track_html_ape(website, link_only=True) try: raw_response = urllib2.urlopen(link.link_content) except: return AQ_render_to_response(request, 'base/custom_error.html', { 'errmsg': RSS_TIMEOUT, }, context_instance=RequestContext(request)) tree = XML(raw_response.read()) for node in tree.getiterator('link'): domain_position = node.text.find(".com") + 4 node.text = tracking_url + "&url=" + node.text[domain_position:] return render_to_response("blank_xml_template.html", {"XML": tostring(tree)}, mimetype="application/xhtml+xml")
def parseResponse(self, xml): tt = [ pywbem.tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall('.//INSTANCE') ] return [pywbem.tupleparse.parse_instance(x) for x in tt]
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 parse_item (data): tree = fromstring(data) title = lxml.html.fromstring(tree.find('title').text).text_content() text = lxml.html.fromstring(tostring(tree.find('text'))).text_content() doc_id = tree.attrib.get('itemid') return doc_id, title, text
def parseResponse(self, xml): tt = [ pywbem.tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall('.//CLASS') ] return [pywbem.tupleparse.parse_class(x) for x in tt]
def parseResponse(xml): res = [] for x in xml.findall('.//VALUE.NAMEDINSTANCE'): s = tostring(x) tt = pywbem.tupletree.xml_to_tupletree(s) r = pywbem.tupleparse.parse_value_namedinstance(tt) res.append(r) return res
def parseResponse(self, xml): tt = [ tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall('.//CLASSNAME') ] return [tupleparse.parse_classname(x) for x in tt]
def parseResponse(self, xml): tt = [ tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall('.//VALUE.NAMEDINSTANCE') ] return [tupleparse.parse_value_namedinstance(x) for x in tt]
def xmltidy(text): """send back good lookin' xml (basically a syntax checker)""" try: elem = XML(text) text = tostring(elem) return text except: #print text return ''
def parseResponse(self, xml): tt = [pywbem.tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall(".//INSTANCENAME")] names = [pywbem.tupleparse.parse_instancename(x) for x in tt] [setattr(n, "namespace", self.namespace) for n in names] return names
def parseResponse(self, xml): if len(xml.findall('.//INSTANCENAME')) > 0: tt = [ pywbem.tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall('.//INSTANCENAME') ] return [pywbem.tupleparse.parse_instancename(x) for x in tt] else: tt = [ pywbem.tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall('.//OBJECTPATH') ] return [pywbem.tupleparse.parse_objectpath(x)[2] for x in tt]
def main(): parser = argparse.ArgumentParser(add_help=False, prog='modulemng') subparsers = parser.add_subparsers(title='subcommands', help='valid subcommands', dest="sub_command") get = subparsers.add_parser('get') get.add_argument("module", help="module", default=None) list = subparsers.add_parser('list') list.add_argument("-d", help="module details", dest="details", action="store_true", default=False) help = subparsers.add_parser('help') args = parser.parse_args() if args.sub_command == "help": parser.print_help() return 0 # retrieve all modules from file system top = Element('modules') # get if args.sub_command == "get": m = searchModule(args.module) if m != None: top.append(m.toElementTree(True)) print tostring(top) return 0 print 'module not found' return 1 # list all_modules = browseModules() for type, modules in all_modules.items(): for module in modules.values(): em = module.toElementTree(args.details) top.append(em) print tostring(top) return 0
def sendConfigurationKillCommand(theurl,jobId): """ Send a SOAP command to the job control to kill a xdaq process: theurl = URL of the job control jobid = job id of the xdaq process """ ff=theurl.split(':') contextPort=ff[2] host=ff[1][2:len(ff[1])] thelid = 10 port=9999 msg = '<?xml version="1.0" encoding="UTF-8"?> \n' msg = msg+ '<SOAP-ENV:Envelope ' msg = msg+ ' SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"' msg = msg+ ' xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"' msg = msg+ ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' msg = msg+ ' xmlns:xsd="http://www.w3.org/2001/XMLSchema"' msg = msg+ ' xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"' msg = msg+ '>\n' msg = msg+ '<SOAP-ENV:Header>\n' msg = msg+ '</SOAP-ENV:Header>\n' msg = msg+ '<SOAP-ENV:Body>\n' # msg = msg+ '<xdaq:startXdaqExe xmlns:xdaq="urn:xdaq-soap:3.0" execPath="/opt/xdaq/bin/xdaq.exe" user="******" >\n' msg = msg+ '<xdaq:killExec user="******" jid="'+jobId+'" xmlns:xdaq="urn:xdaq-soap:3.0" />\n' msg = msg+ '</SOAP-ENV:Body>\n' msg = msg+ '</SOAP-ENV:Envelope>\n' smsg0=msg.encode("utf_8") fout=open("toto.txt","w+") fout.write(smsg0) tree = ET.XML(msg) smsg=tostring(tree) sm1=smsg.replace('ns0','SOAP-ENV') sm2=sm1.replace('ns1','xdaq') sm3=sm2.replace('ns2','xc') sm4=sm3.replace('ns3','xc') print sm4 print "======================================================================" saction = 'urn:xdaq-application:lid=%d' % (thelid) #params = urllib.urlencode(msg) headers = {"Content-Type":"text/xml", "charset":"utf-8","Content-Description":"SOAP Message", "SOAPAction":saction} myurl = host+ ":%d" % port conn = httplib.HTTPConnection(myurl) myreq=conn.request("POST", "/cgi-bin/query", smsg, headers) response = conn.getresponse() if (response.status != 200): print response.status, response.reason data = response.read() print response.status conn.close() return data
def parseResponse(self, xml): tt = [ pywbem.tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall('.//INSTANCENAME') ] names = [pywbem.tupleparse.parse_instancename(x) for x in tt] [setattr(n, 'namespace', self.namespace) for n in names] return names
def create_solr_doc(self, info, status="private"): """Creates an in memory xml file for solr import under the format: dd_date nsf_id status summary description Args: info: A list containing the data needed for solr doc status: The public/private status of the prop Returns: Returns a string of XML """ import xml.etree.ElementTree as xml import elementtree.ElementTree as ET from elementtree.ElementTree import XML, fromstring, tostring for val in info: print val root = xml.Element("add") child = xml.Element("doc") root.append(child) field = xml.Element("field") field.attrib["name"] = "id" field.text = info[0] child.append(field) field = xml.Element("field") field.attrib["name"] = "date" field.text = info[1] child.append(field) field = xml.Element("field") field.attrib["name"] = "Project_Summary" field.text = info[2] child.append(field) #only add status and full description if private if status == "private": field = xml.Element("field") field.attrib["name"] = "Project_Description" field.text = info[3] child.append(field) field = xml.Element("field") field.attrib["name"] = "status" field.text = info[4] child.append(field) return tostring(root, 'utf-8')
def main(): parser = argparse.ArgumentParser(add_help=False, prog="modulemng") subparsers = parser.add_subparsers(title="subcommands", help="valid subcommands", dest="sub_command") get = subparsers.add_parser("get") get.add_argument("module", help="module", default=None) list = subparsers.add_parser("list") list.add_argument("-d", help="module details", dest="details", action="store_true", default=False) help = subparsers.add_parser("help") args = parser.parse_args() if args.sub_command == "help": parser.print_help() return 0 # retrieve all modules from file system top = Element("modules") # get if args.sub_command == "get": m = searchModule(args.module) if m != None: top.append(m.toElementTree(True)) print tostring(top) return 0 print "module not found" return 1 # list all_modules = browseModules() for type, modules in all_modules.items(): for module in modules.values(): em = module.toElementTree(args.details) top.append(em) print tostring(top) return 0
def process(self, xml): """Initiate an SSL connection and return the xmlresponse """ conn = ssl.HTTPSConnection(self._site) # setup the HEADERS log.info('Setting up request headers') conn.putrequest('GET', self._path+'?xmldata='+quote(tostring(xml))) conn.putheader('Content-Type', 'text/xml') conn.endheaders() log.info('Getting the response from the Virtual Merchant site') result = conn.getresponse().read() xmlresponse = fromstring(result) return xmlresponse
def encode_XMLDict(self, mapping): """!TXT!""" def encode(key, value): element = Element(key) if isinstance(value, NoneType): element.attrib['type'] = 'none' elif isinstance(value, BooleanType): element.attrib['type'] = 'bool' element.attrib['value'] = value and 'true' or 'false' elif isinstance(value, ComplexType): element.attrib['type'] = 'complex' element.attrib['re'] = repr(value.real) element.attrib['im'] = repr(value.imag) elif isinstance(value, FloatType): element.attrib['type'] = 'float' element.attrib['value'] = repr(value) elif isinstance(value, IntType): element.attrib['type'] = 'int' element.attrib['value'] = repr(value) elif isinstance(value, LongType): element.attrib['type'] = 'long' element.attrib['value'] = repr(value) elif isinstance(value, StringType) or isinstance(value, UnicodeType): element.attrib['type'] = 'cdata' element.text = u"<![CDATA[%s]]>" % value elif isinstance(value, DictType): element.attrib['type'] = 'dict' for key in value.keys(): element.append(encode(key, value[key])) elif isinstance(value, ListType): element.attrib['type'] = 'list' for subvalue in value: element.append(encode('value', subvalue)) elif isinstance(value, TupleType): element.attrib['type'] = 'tuple' for subvalue in value: element.append(encode('value', subvalue)) else: raise TypeError("Encoding of %s not supported (Key: %s)" % (repr(value), key)) return element root = Element("data") for key in mapping.keys(): root.append(self.encode(key, mapping[key])) return tostring(root)
def parse_xml (data, keywords): tree = fromstring(data) title = lxml.html.fromstring(tree.find('title').text).text_content() text = lxml.html.fromstring(tostring(tree.find('text'))).text_content() words = [sanitize(word) for word in title.split(' ') if len(word) > 0] words.extend([sanitize(word) for word in text.split(' ') if len(text) > 0]) for word in words: if len(word) == 0: continue if word not in keywords: keywords[word] = 1 else: keywords[word] += 1
def FormattedContent(self, report_obj, chart_style, request): from atrinsic.base.models import AqWidget,UserAqWidget x = self.widget_id widget = AqWidget.objects.get(pk=self.widget_id) var_columns = None if self.user_widget_id != None: user_widget = UserAqWidget.objects.get(pk=self.user_widget_id) if user_widget.custom_columns != None: var_columns = user_widget.custom_columns if (var_columns == None) & (self.data_columns != None): var_columns = self.data_columns else: var_columns = widget.data_columns if var_columns.find(",") > 0: col1,col2 = var_columns.split(",") else: col1 = var_columns col2 = None columns = { 'var1': col1, 'var2':col2 } if chart_style == "table": html = self.getReportHTML(report_obj) return html elif chart_style == "json-array": import cjson return cjson.encode(report_obj.RenderContents()) elif chart_style == "json": import cjson json = self.get_json(report_obj) return cjson.encode(json) elif chart_style == "xml": from elementtree import ElementTree from elementtree.ElementTree import Element,tostring,SubElement,ElementTree,dump xmldict = {} xmldict["xml"] = self.get_json(report_obj) root = Element("xml") for row in xmldict["xml"]: item_element = SubElement(root,"item") for field in row: SubElement(item_element,field).text = row[field] return tostring(root) else: return self.getAQChart(request=request,chart_style=chart_style,report_obj=report_obj,columns=columns)
def solr_list_to_xml(self, string): """Takes a formatted list of solr data, formats it into xml and returns it as a string Args: string = list of string data to put into solr entry Returns: utf-8 formatted xml string to be fed into solr Raises: None """ root = xml.Element("add") child = xml.Element("doc") root.append(child) field = xml.Element("field") field.attrib["name"] = "id" field.text = string[0] field = xml.Element("field") field.attrib["name"] = "date" field.text = string[1] child.append(field) field = xml.Element("field") field.attrib["name"] = "Project_Summary" field.text = string[2] child.append(field) #only add status and full description if private field = xml.Element("field") field.attrib["name"] = "Project_Description" field.text = string[3] child.append(field) field = xml.Element("field") field.attrib["name"] = "status" field.text = string[4] child.append(field) return tostring(root, "utf-8")
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 process_rss_feed(request,link_id_encoded,website_encode_id): from atrinsic.base.models import Link,Website from atrinsic.web.helpers import base36_decode from elementtree.ElementTree import XML,tostring import urllib2 link = Link.objects.get(pk=base36_decode(link_id_encoded)) website = Website.objects.get(pk=base36_decode(website_encode_id)) tracking_url = link.track_html_ape(website,link_only=True) try: raw_response = urllib2.urlopen(link.link_content) except: return AQ_render_to_response(request, 'base/custom_error.html', { 'errmsg' : RSS_TIMEOUT, }, context_instance=RequestContext(request)) tree = XML(raw_response.read()) for node in tree.getiterator('link'): domain_position = node.text.find(".com") + 4 node.text = tracking_url + "&url=" + node.text[domain_position:] return render_to_response("blank_xml_template.html", {"XML":tostring(tree)}, mimetype="application/xhtml+xml")
def inst(self,irc,msg,args): """<institution> Look up a oclc participating institution by code """ from elementtree.ElementTree import tostring from socket import setdefaulttimeout from re import sub setdefaulttimeout(60) ns = 'http://www.w3.org/1999/xhtml' inst = args[0] self.log.info("looking up oclc institution %s" % inst) url = "http://www.oclc.org/common/cgi-oclc/pi.pl?max=1&sym=%s" % inst response = "" try: tree = TidyHTMLTreeBuilder.parse( urlopen(url) ) root = tree.getroot() info = tostring(root.findall('.//{%s}font'%ns)[8]) response = sub("<.*?>",'', info.replace("\n",' ')) except: response = "sorry no hits for %s" % inst irc.reply(response)
def inst(self, irc, msg, args): """<institution> Look up a oclc participating institution by code """ from elementtree.ElementTree import tostring from socket import setdefaulttimeout from re import sub setdefaulttimeout(60) ns = 'http://www.w3.org/1999/xhtml' inst = args[0] self.log.info("looking up oclc institution %s" % inst) url = "http://www.oclc.org/common/cgi-oclc/pi.pl?max=1&sym=%s" % inst response = "" try: tree = TidyHTMLTreeBuilder.parse(urlopen(url)) root = tree.getroot() info = tostring(root.findall('.//{%s}font' % ns)[8]) response = sub("<.*?>", '', info.replace("\n", ' ')) except: response = "sorry no hits for %s" % inst irc.reply(response)
def formatSystemStatus(info): top_node = Element('systemstatus') SubElement(top_node, 'datetime', {'value': time.strftime(TIME_FORMAT, info['datetime'])}) for cpu in info['cpus']: cpu_node = SubElement(top_node, 'cpu', { 'value': cpu['value'], 'used': cpu['used'], }) cores_node = SubElement(cpu_node, 'cores') for core in cpu['cores']: SubElement(cores_node, 'core', core) SubElement(top_node, 'ram', info['ram']) disks = SubElement(top_node, 'disks') for disk in info['disks']: SubElement(disks, 'disk', disk) return tostring(top_node)
def category_tree(id=None): """ Creates an unnumbered list of the categories. For example: <ul> <li>Books <ul> <li>Science Fiction <ul> <li>Space stories</li> <li>Robot stories</li> </ul> </li> <li>Non-fiction</li> </ul> </ul> """ active_cat = None if id: active_cat = Category.objects.get(id=id) root = Element("ul") for cats in Category.objects.filter(parent__isnull=True): recurse_for_children(cats, root, active_cat) return tostring(root, 'utf-8')
def formatSystemStatus(info): top_node = Element('systemstatus') SubElement(top_node, 'datetime', { 'value': time.strftime(TIME_FORMAT, info['datetime']) }) for cpu in info['cpus']: cpu_node = SubElement(top_node, 'cpu', { 'value': cpu['value'], 'used': cpu['used'], }); cores_node = SubElement(cpu_node, 'cores') for core in cpu['cores']: SubElement(cores_node, 'core', core) SubElement(top_node, 'ram', info['ram']); disks = SubElement(top_node, 'disks') for disk in info['disks']: SubElement(disks, 'disk', disk); return tostring(top_node)
def parseResponse(self, xml): tt = pywbem.tupletree.xml_to_tupletree(tostring(xml.find(".//CLASS"))) return pywbem.tupleparse.parse_class(tt)
def parseResponse(self, xml): tt = [pywbem.tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall(".//CLASS")] return [pywbem.tupleparse.parse_class(x) for x in tt]
def parseResponse(self, xml): tt = pywbem.tupletree.xml_to_tupletree(tostring(xml.find(".//INSTANCENAME"))) return pywbem.tupleparse.parse_instancename(tt)
#!/usr/bin/env python from sys import argv from elementtree.ElementTree import Element, SubElement, tostring if __name__ == '__main__': dir = argv[1] imagename = dir.split('/')[-1] e = Element("Image", name=imagename) for line in open("%s/base.ConfigFile" % (dir)).readlines(): SubElement(e, "ConfigFile", name=line.strip()) for line in open("%s/base.Package" % (dir)).readlines(): SubElement(e, "Package", name=line.strip()) for line in open("%s/base.Service" % (dir)).readlines(): SubElement(e, "Service", name=line.strip().split()[0]) print(tostring(e))
def parseResponse(self, xml): tt = [pywbem.tupletree.xml_to_tupletree(tostring(x)) for x in xml.findall(".//VALUE.NAMEDINSTANCE")] return [pywbem.tupleparse.parse_value_namedinstance(x) for x in tt]
def format(self,obj): root = self._format(self._elemap,obj) return tostring(root)
def format(self, obj): root = self._format(self._elemap, obj) return tostring(root)
print("HTMLBuilder took ", (t2 - t1)) if 0: print(currentTag("<xsl")) print(currentTag("<xsl:")) print(currentTag("<xsl:tag")) print(currentTag("text><xsl:tag")) # print nodemap html = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> """ tree = getService().getTreeForURI("Text.html", html) print(tostring(tree.root)) html = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <HEAD> <TITLE>Mozilla Cross-Reference</TITLE> <link HREF=http://www.activestate.com/global.css rel="stylesheet" type="text/css"> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000EE" VLINK="#551A8B" ALINK="#FF0000"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr>
from elementtree import ElementTree as et from elementtree.ElementTree import tostring from com.finnean.io.reader import XMLReader reader = XMLReader.XMLReader(r'D:\Lib\Butters\results.xml') root = et.XML(reader.read()) results = root.findall('results') df = open(r'D:\Lib\Butters\new-results.xml', 'w') df.write('''<?xml version="1.0"?>\n''') df.write('''<report>\n''') df.write(tostring(results[0])) df.write('''</report>\n''') df.close()
headers, xml = client.request(BASE + "notes.xml") doc = ElementTree.fromstring(xml) for note in doc.findall('note'): print "%s: %s" % (note.find('date').text, note.find('body').text) newNote = Element("note") date = SubElement(newNote, "date") date.attrib['type'] = "date" date.text = time.strftime("%Y-%m-%d", time.localtime()) body = SubElement(newNote, "body") body.text = "A test note" headers, ignore = client.request(BASE + "notes.xml", "POST", body=tostring(newNote), headers={'content-type': 'application/xml'}) newURI = headers['location'] modifiedBody = Element("note") body = SubElement(modifiedBody, "body") body.text = "This note has been modified" client.request(newURI, "PUT", body=tostring(modifiedBody), headers={'content-type': 'application/xml'}) showNotes() client.request(newURI, "DELETE")
def custom_sort(b, a): if a[0] in tostring(items[b[0]]): return 1 return -1
print "HTMLBuilder took ", (t2 - t1) if 0: print currentTag("<xsl") print currentTag("<xsl:") print currentTag("<xsl:tag") print currentTag("text><xsl:tag") # print nodemap html = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> """ tree = getService().getTreeForURI("Text.html", html) print tostring(tree.root) html = u"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <HEAD> <TITLE>Mozilla Cross-Reference</TITLE> <link HREF=http://www.activestate.com/global.css rel="stylesheet" type="text/css"> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000EE" VLINK="#551A8B" ALINK="#FF0000"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr>
print "HTMLBuilder took ",(t2-t1) if 0: print currentTag("<xsl") print currentTag("<xsl:") print currentTag("<xsl:tag") print currentTag("text><xsl:tag") #print nodemap html = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> """ tree = getService().getTreeForURI("Text.html", html) print tostring(tree.root) html = u"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <HEAD> <TITLE>Mozilla Cross-Reference</TITLE> <link HREF=http://www.activestate.com/global.css rel="stylesheet" type="text/css"> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000EE" VLINK="#551A8B" ALINK="#FF0000"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr>
etree = ElementTree(file=StringIO.StringIO(content)) feed = XML(content) print etree print feed #print len(feed) #print feed[0] #print feed.keys() ATOM = "http://www.w3.org/2005/Atom" entry = etree.getiterator('{%s}entry'%ATOM)[0] new_lin = SubElement(entry, '{%s}link'%ATOM) new_lin.set('rel', 'source') new_lin.set('href', 'http://somthing.org') title = etree.findall('{%s}title'%ATOM)[0] print tostring(title) missing = etree.findall('{%s}missing'%ATOM) print missing for e in etree.findall('//{%s}link'%ATOM): print e.get('rel', 'alternate') s = StringIO.StringIO() etree.write(s) s.seek(0) print s.getvalue()