当前位置: 首页>>代码示例>>Python>>正文


Python XML.find方法代码示例

本文整理汇总了Python中xml.etree.ElementTree.XML.find方法的典型用法代码示例。如果您正苦于以下问题:Python XML.find方法的具体用法?Python XML.find怎么用?Python XML.find使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在xml.etree.ElementTree.XML的用法示例。


在下文中一共展示了XML.find方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _process_result

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
    def _process_result(self):
        document = XML(self._xml_data)

        if document.find(_FIND_DESCRIPTION) is None:
            logging.debug('Bundle %s not available in the server for the '
                'version %s', self._bundle.get_bundle_id(), config.version)
            version = None
            link = None
            size = None
        else:
            try:
                version = NormalizedVersion(document.find(_FIND_VERSION).text)
            except InvalidVersionError:
                logging.exception('Exception occured while parsing version')
                version = '0'

            link = document.find(_FIND_LINK).text

            try:
                size = long(document.find(_FIND_SIZE).text) * 1024
            except ValueError:
                logging.exception('Exception occured while parsing size')
                size = 0

        global _fetcher
        _fetcher = None
        self._completion_cb(self._bundle, version, link, size, None)
开发者ID:ajaygarg84,项目名称:sugar,代码行数:29,代码来源:aslo.py

示例2: isatom

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
def isatom(body):
    """Answers if the given response body looks like ATOM."""
    root = XML(body)
    return \
        root.tag == XNAME_FEED and \
        root.find(XNAME_AUTHOR) is not None and \
        root.find(XNAME_ID) is not None and \
        root.find(XNAME_TITLE) is not None
开发者ID:huit,项目名称:splunk-sdk-python,代码行数:10,代码来源:test_binding.py

示例3: printXml

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
def printXml(text):
    xml = XML(text)

    print "%s\t%.2f\t%.2f\t%s" % (
        xml.get("name"),
        eval(xml.find("price").text),
        eval(xml.find("offer").text),
        "up" if xml.find("up").text == "True" else "down",
    )
开发者ID:fabio2006,项目名称:amq-in-action-example-src,代码行数:11,代码来源:book.py

示例4: _get_capabilities

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
    def _get_capabilities(self):
        xml = XML(self.conn.getCapabilities())
        capabilities = {
            'canonical': xml.find('guest/arch[@name="x86_64"]/machine[@canonical]').attrib['canonical'],
            'topology': {k: int(v) for k, v in xml.find('host/cpu/topology').attrib.items()},
            'model': xml.find('host/cpu/model').text,
            'toggleable': [e.tag for e in xml.findall('guest/arch[@name="x86_64"]/../features/*[@toggle]')],
        }

        features = [element.attrib['name'] for element in self._features.findall('host/cpu/feature')]
        features.extend(self._list_features(capabilities['model']))

        capabilities['features'] = features

        return capabilities
开发者ID:ponycloud,项目名称:python-ponyvirt,代码行数:17,代码来源:hypervisor.py

示例5: _dispatchSoapRequest

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
 def _dispatchSoapRequest(self, request):
     try:
         try:
             envelope = XML(request.soap_data)
             body = envelope.find("{http://schemas.xmlsoap.org/soap/envelope/}Body")
             # determine UPnP action
             action = body.find("{%s}%s" % (request.soap_ns, request.soap_action))
             # look up the action in the service
             upnp_action = self.service._actions[request.soap_action]
             # build a list of the action arguments
             in_args = {}
             for arg in action:
                 in_args[arg.tag] = arg.text
             # execute the UPnP action
             logger.log_debug("executing %s#%s" % (self.service.serviceID, request.soap_action))
             out_args = upnp_action(request, self.service, in_args)
             # return the action response
             env = Element("s:Envelope")
             env.attrib['xmlns:s'] = "http://schemas.xmlsoap.org/soap/envelope/"
             env.attrib['s:encodingStyle'] = "http://schemas.xmlsoap.org/soap/encoding/"
             env.attrib['xmlns:i'] = "http://www.w3.org/1999/XMLSchema-instance"
             body = SubElement(env, "s:Body")
             resp = SubElement(body, "u:%sResponse" % request.soap_action)
             resp.attrib['xmlns:u'] = request.soap_ns
             for (name,type,value) in out_args:
                 arg = SubElement(resp, name)
                 arg.attrib["i:type"] = type
                 arg.text = value
             output = xmlprint(env)
             return HttpResponse(200, headers={'EXT': ''}, stream=output)
         except UPNPError, e:
             raise e
         except Exception, e:
             logger.log_error("caught unhandled exception: %s" % e)
             raise UPNPError(500, "Internal server error")
开发者ID:msfrank,项目名称:Higgins,代码行数:37,代码来源:control_resource.py

示例6: get_cell_group

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
	def get_cell_group(self):
		ncx_file = self.get_ncx_file()
		with open(ncx_file,'r') as f:
			xml_str = f.read()
		neuroml = XML(xml_str) # The NeuroML file in parsable form.  
		cell_group = neuroml.find("object/void[@property='allSimConfigs']/void/object/void[@property='cellGroups']/void/string").text
		return cell_group
开发者ID:BlueBrain,项目名称:neuronunit,代码行数:9,代码来源:models.py

示例7: identify

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
 def identify(self, geosGeometry, geometryFieldName, layers, url, username, password):
     """
         Assuming :
         Url like http://localhost:8080/geoserver/wfs
         layers like geonode:capa
         geosGeometry is in Lambert72
     """
     #TODO input checking
     gmlString = geosGeometry.ogr.gml
     payload = self._buildWfsIntersectRequest(gmlString, layers, geometryFieldName)
     #Verify False to avoid certificate not trusted problems
     r = requests.post(url, data = payload, auth=(username, password), verify=False)
     tree = XML(r.text)
     if tree.tag == "{http://www.opengis.net/ogc}ServiceExceptionReport":
         #We Got OGC Error. Find the root cause and throw a proper Exception
         se = tree.find('{http://www.opengis.net/ogc}ServiceException')
         raise Exception(str(se.text).strip())
     else:
         clean_results = []
         features = tree.findall('{http://www.opengis.net/gml}featureMember')
         for feature in features:
             attributes = {}
             for child in feature:
                 for child_elem in child:
                     tag_name = child_elem.tag.split('}')[-1] #Get rid of namespace
                     if child_elem.text is not None:
                         attributes[tag_name] = child_elem.text
                     else:
                         attributes[tag_name] = ""
             clean_results.append(attributes)
         return clean_results
开发者ID:IMIO,项目名称:imio_geonode,代码行数:33,代码来源:querier.py

示例8: updatequotewithparameters

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
    def updatequotewithparameters(self, quote_id,ExternalReference,Grossvalue,netvalue,postingDate,RefDate,SoldToParty,SoldToPartyAdd,Status,TaxAmt,ValidFrm,ValidTo):
        logging.info("SAP is sending quote with more parameters")
        logging.info(locals())
        logging.info("CONNECTING TO SALESFORCE PARTNER WSDL FOR SESSION ID")
        url = "https://login.salesforce.com/services/Soap/u/28.0"

        data = """<?xml version="1.0" encoding="UTF-8"?>
                <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:partner.soap.sforce.com">
                   <soapenv:Header>
                        <urn:CallOptions>
                            <urn:client></urn:client>
                            <urn:defaultNamespace></urn:defaultNamespace>
                        </urn:CallOptions>
                        <urn:LoginScopeHeader>
                            <urn:organizationId></urn:organizationId>
                            <urn:portalId></urn:portalId>
                        </urn:LoginScopeHeader>
                   </soapenv:Header>
                   <soapenv:Body>
                      <urn:login>
                          <urn:username>{{username}}</urn:username>
                          <urn:password>{{password}}</urn:password>
                      </urn:login>
                   </soapenv:Body>
                </soapenv:Envelope>"""
        t = Template(data)
        c = Context({
#            "username": "[email protected]",
#            "password": "venkatesh123ffk0XM9LgYDkBpmRJEJ6PuL7g"
#            "username": "[email protected]",
#            "password": "sfdc*123Lw8jQCSB0ygTot7YagKHoiBJK"
            "username": "[email protected]",
            "password": "iservice123ZmYFLUDAgDlyV068L9mFxyNF5"
        })
        data = t.render(c)

        logging.info("SENDING:")
        logging.info(data)

        headers = {
            'Content-Type': 'text/xml; charset=utf-8',
            'SOAPAction' : 'https://login.salesforce.com/services/Soap/u/28.0'
        }
#        httplib2.debuglevel = 1 
        
        head = httplib2.Http()
    #    head.follow_all_redirects = True
        response, content = head.request(url, "POST", smart_str(data), headers)
        logging.info("########### SESSION ID response ###############%s"%response)
        logging.info("########## SESSION ID content ############## \n %s"%pretty(content))
        if response.get('status') == '200':
            logging.info("GOT THE SESSION ID FROM SALESFORCE")
            xml = XML(content)
            session_response=xml.find("{http://schemas.xmlsoap.org/soap/envelope/}Body").getchildren()[0]
            session_id = session_response[0][4].text
            quote_id_to_sf(session_id,quote_id,ExternalReference,Grossvalue,netvalue,postingDate,RefDate,SoldToParty,SoldToPartyAdd,Status,TaxAmt,ValidFrm,ValidTo)
        else:
            return content

        return "OK"
开发者ID:venkatesh22,项目名称:sap_sf,代码行数:62,代码来源:soap1.py

示例9: get_journal

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
def get_journal(pmid):
    MAXURLTRIES = 5
    numTries = 0
    success = False
    link = esummary % (pmid)
    req = Request(link)
    while numTries < MAXURLTRIES and success == False: 
        try: 
            handle = urlopen(req)
            success = True
        except (URLError, HTTPError, BadStatusLine, ParseError):
            print ' failed %d times' % numTries 
            numTries += 1
    if numTries == MAXURLTRIES:
        journal_title = None 
        return journal_title
    try:                        
        data = handle.read()
        xml = XML(data)    
        journalXML = xml.find('.//FullJournalName')
        if journalXML is not None:
            journal_title = journalXML.text
        else:
            journal_title = None
        return journal_title
    except Exception:
        journal_title = None 
        return journal_title
开发者ID:gitter-badger,项目名称:neuroelectro_org,代码行数:30,代码来源:pubmed_functions.py

示例10: __downloader_complete_cb

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
    def __downloader_complete_cb(self, downloader, result):
        if isinstance(result, Exception):
            self.emit('check-complete', result)
            return

        if result is None:
            _logger.error('No XML update data returned from ASLO')
            return

        document = XML(result.get_data())

        if document.find(_FIND_DESCRIPTION) is None:
            _logger.debug('Bundle %s not available in the server for the '
                          'version %s',
                          self._bundle.get_bundle_id(),
                          config.version)
            version = None
            link = None
            size = None
            self.emit('check-complete', None)
            return

        try:
            version = NormalizedVersion(document.find(_FIND_VERSION).text)
        except InvalidVersionError:
            _logger.exception('Exception occurred while parsing version')
            self.emit('check-complete', None)
            return

        link = document.find(_FIND_LINK).text

        try:
            size = long(document.find(_FIND_SIZE).text) * 1024
        except ValueError:
            _logger.exception('Exception occurred while parsing size')
            size = 0

        if version > NormalizedVersion(self._bundle.get_activity_version()):
            result = BundleUpdate(self._bundle.get_bundle_id(),
                                  self._bundle.get_name(), version, link, size)
        else:
            result = None

        self.emit('check-complete', result)
开发者ID:PoetticJustice,项目名称:sugar,代码行数:46,代码来源:aslo.py

示例11: get_status

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
def get_status(url = os.environ['STATUS_URL']):
    response = urllib2.urlopen(url)
    try:
        xml = XML(response.read())
    finally:
        response.close()

    result = {}

    el = xml.find('sms')
    result_d = result['sms'] = {}
    result_d['received'] = {'total': int(el.findtext('received/total')),
     'queued': int(el.findtext('received/queued'))}
    result_d['sent'] = {'total': int(el.findtext('sent/total')),
     'queued': int(el.findtext('sent/queued'))}
    result_d['storesize'] = int(el.findtext('storesize'))

    el = xml.find('dlr')
    result_d = result['dlr'] = {}
    result_d['received'] = {'total': int(el.findtext('received/total'))}
    result_d['sent'] = {'total': int(el.findtext('sent/total'))}

    result_d['queued'] = int(el.findtext('queued'))

    els = xml.find('smscs').findall('smsc')
    result_d = result['smscs'] = []
    for el in els:
        result_d.append({
            'id': el.findtext('id'),
            'admin_id': el.findtext('admin-id'),
            'received': {
                'sms': int(el.findtext('sms/received')),
                'dlr': int(el.findtext('dlr/received'))
            },
            'sent': {
                'sms': int(el.findtext('sms/sent')),
                'dlr': int(el.findtext('dlr/sent'))
            },
            'failed' : int(el.findtext('failed')),
            'queued' : int(el.findtext('queued')),
            'status' : el.findtext('status').split(' ', 2)[0]
        })

    return result
开发者ID:billux,项目名称:munin-kannel-plugins,代码行数:46,代码来源:kannel_util.py

示例12: open_rest

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
 def open_rest(self):
     self.rest = _read(codecs.open(self.path, 'r', 'utf-8'))
     xhtml = publish_string(self.rest, writer_name='xml',
                            settings_overrides=dict(report_level=5))
     x = XML(xhtml) # parse the XML text
     t = x.find('title')
     try:
         self.title = t.text #extract its title
     except AttributeError:
         self.title = 'Untitled'
开发者ID:messiahwang,项目名称:gitpublish,代码行数:12,代码来源:core.py

示例13: pmc_id_to_pmid

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
def pmc_id_to_pmid(pmc_id_list):
    pmid_list = []
    for pmcid in pmc_id_list:
        link = pmc_pmid_url % (pmcid)
        req = Request(link)
        handle = urlopen(req)
        data = handle.read()
        xml = XML(data) 
        pmid = int(xml.find('record').attrib['pmid'])
        pmid_list.append(pmid)
    return pmid_list
开发者ID:lessc0de,项目名称:neuroelectro_org,代码行数:13,代码来源:pmc_article_search.py

示例14: _list_alchemy_results

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
def _list_alchemy_results(xml, relevance):
    dom = XML(xml)
    results = []
    if dom.find("status").text == "OK":
        for concept in dom.findall(".//concept"):
            if float(concept.find("relevance").text) > relevance:
                results.append(concept.find("text").text)
        for kw in dom.findall(".//keyword"):
            if float(kw.find("relevance").text) > relevance:
                results.append(kw.find("text").text)
    return results
开发者ID:jean,项目名称:collective.taghelper,代码行数:13,代码来源:utilities.py

示例15: _get_build_link_from_response

# 需要导入模块: from xml.etree.ElementTree import XML [as 别名]
# 或者: from xml.etree.ElementTree.XML import find [as 别名]
 def _get_build_link_from_response(self, response):
     """
     Extract the link to the new build from the XML returned - unfortunately bamboo api doesn't give back json data
     for this method
     :param response: response text of the post request to kick off the new build
     :return: href of the link to the new build - used to get the status
     """
     response_xml = XML(response)
     self.log.debug("Parsing build response for build link:" + response)
     build_link = response_xml.find("link").attrib['href']
     self.log.debug("Found build link: " + build_link)
     return build_link
开发者ID:hmcmanus,项目名称:scriptural,代码行数:14,代码来源:bamboo_build_runner.py


注:本文中的xml.etree.ElementTree.XML.find方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。