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


Python ElementTree.XML类代码示例

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


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

示例1: __init__

 def __init__(self, **kwargs):
     self._issue_date_utc = None
     self._expiration_date_utc = None
     self.is_trial = "false"
     if "xml_node" in kwargs:
         xml_node = kwargs["xml_node"]
     else:
         xml_node = XML(kwargs["xml"])
     xml_attrs = xml_node.attrib
     attrs = {
         "id": "licenseId",
         "user_id": "userId",
         "payment_plan_id": "paymentPlanId",
         "issue_date_utc": "issueDateUTC",
         "expiration_date_utc": "expirationDateUTC",
         "is_trial": "is_trial",
     }
     for k, v in attrs.items():
         if v in xml_attrs:
             setattr(self, k, xml_attrs[v])
         else:
             setattr(self, k, None)
     features = []
     for node in xml_node.findall(".//feature"):
         feature = Feature(xml_node=node)
         features.append(feature)
     self.features = features
     super().__init__(**kwargs)
开发者ID:marcelow,项目名称:licensario-python,代码行数:28,代码来源:license.py

示例2: getNotifications

    def getNotifications(self, rurl):
        """
        Get a list of L{Notification} objects for the specified notification collection.

        @param rurl: a user's notification collection URL
        @type rurl: L{URL}
        """

        assert(isinstance(rurl, URL))

        # List all children of the notification collection
        results = self.getPropertiesOnHierarchy(rurl, (davxml.getcontenttype,))
        items = results.keys()
        items.sort()
        notifications = []
        for path in items:
            path = urllib.unquote(path)
            nurl = URL(url=path)
            if rurl == nurl:
                continue
            props = results[path]
            if props.get(davxml.getcontenttype, "none").split(";")[0] in ("text/xml", "application/xml"):
                data, _ignore_etag = self.readData(URL(url=path))
                node = XML(data)
                if node.tag == str(csxml.notification):
                    for child in node.getchildren():
                        if child.tag == str(csxml.invite_notification):
                            notifications.append(InviteNotification().parseFromNotification(nurl, child))
                        elif child.tag == str(csxml.invite_reply):
                            notifications.append(InviteReply().parseFromNotification(nurl, child))

        return notifications
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:32,代码来源:clientsession.py

示例3: __init__

    def __init__(self, host='localhost', port=2812, username=None, password='', https=False):

        if not port:
            port = 2812

        port = int(port)
        self.baseurl = (https and 'https://%s:%i' or 'http://%s:%i') % (host, port)
        url = self.baseurl + '/_status?format=xml'

        req = urllib2.Request(url)

        if username:
            base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
            authheader = "Basic %s" % base64string
            req.add_header("Authorization", authheader)

        try:
            handle = urllib2.urlopen(req)
        except urllib2.URLError as e:
            raise Exception(e.reason)

        try:
            response = handle.read()
        except:
            raise Exception("Error while reading")

        try:
            from xml.etree.ElementTree import XML
            root = XML(response)
        except:
            raise Exception("Error while converting to XML")

        for serv_el in root.iter('service'):
            serv = MonitConn.Service(self, serv_el)
            self[serv.name] = serv
开发者ID:ecmanaged,项目名称:monitor-plugins,代码行数:35,代码来源:check_monit.py

示例4: updatequotewithparameters

    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,代码行数:60,代码来源:soap1.py

示例5: getAllArtifactVersions

	def getAllArtifactVersions(self, strGroupID, strArtifactID):
		atVersions = []

		strPath = self.strUrlLuceneSearchGA % (strGroupID, strArtifactID)
		aucContent = self.tRestDriver.get(self.tServerBaseUrl, strPath)
		tSearchResult = XML(aucContent)

		# The search result must be complete.
		if tSearchResult.findtext('tooManyResults')!='false':
			raise Exception("Received a truncated search result!")
	
		# Loop over all results.
		for tNode in tSearchResult.findall('data/artifact'):
			strVersion = tNode.findtext('version')
			if isinstance(strVersion, basestring)==True:
				strVersion = strVersion.strip()
				if strVersion=='SNAPSHOT':
					tVersion = deploy_version.version(0, 0, 0)
				else:
					tVersion = deploy_version.version(strVersion)
				atVersions.append(tVersion)

		# Sort the versions.
		atVersions.sort()

		return atVersions
开发者ID:muhkuh-sys,项目名称:mbs,代码行数:26,代码来源:repository_driver_nexus.py

示例6: pmc_article_search

def pmc_article_search():
    id_list = []
    search_string = '((neuron electrophysiology) OR (neurophysiology) OR ("input resistance") OR ("resting potential" OR "resting membrane potential") OR "LTP" OR "synaptic plasticity" OR "LTD")'
    search_string_quoted = quote(search_string, safeChars)
    #print search_string_quoted
    retstart = 0
    retmax = 20
    link = esearch % (search_string_quoted, retstart, retmax)
    req = Request(link)
    handle = urlopen(req)
    data = handle.read()
    xml = XML(data)    
    num_found_articles = 20#int(xml.find('.//Count').text)
    
    while retstart < num_found_articles:
        link = esearch % (search_string_quoted, retstart, retmax)
        req = Request(link)
        handle = urlopen(req)
        data = handle.read()
        #print data
        xml = XML(data)    
        id_list_temp = xml.findall(".//Id")
        if len(id_list_temp) == 0:
            id_list_temp = int(xml.findall(".//Id"))
        for id_elem in id_list_temp:
            id_list.append(int(id_elem.text))
        retstart += retmax
    return id_list
开发者ID:lessc0de,项目名称:neuroelectro_org,代码行数:28,代码来源:pmc_article_search.py

示例7: gsversion

    def gsversion(self):
        '''obtain the version or just 2.2.x if < 2.3.x
        Raises:
            FailedRequestError: If the request fails.
        '''
        if self._version: return self._version
        about_url = self.service_url + "/about/version.xml"
        response, content = self.http.request(about_url, "GET")
        version = None
        if response.status == 200:
            dom = XML(content)
            resources = dom.findall("resource")
            for resource in resources:
                if resource.attrib["name"] == "GeoServer":
                    try:
                        version = resource.find("Version").text
                        break
                    except:
                        pass

        #This will raise an exception if the catalog is not available
        #If the catalog is available but could not return version information,
        #it is an old version that does not support that
        if version is None:
            self.get_workspaces()
            # just to inform that version < 2.3.x
            version = "2.2.x"
        self._version = version
        return version
开发者ID:MPBA,项目名称:climaatlas,代码行数:29,代码来源:catalog.py

示例8: _dispatchSoapRequest

 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,代码行数:35,代码来源:control_resource.py

示例9: fields

    def fields(self, flat=False):

        data = {}

        resp = requests.get(self.fields_url)
        doc = XML(resp.text)

        if flat:

            for elem in doc.iter('variable'):
                data[elem.attrib['name']] = "%s: %s" % (elem.attrib['concept'], elem.text)

        else:

            for concept_elem in doc.iter('concept'):

                concept = concept_elem.attrib['name']
                variables = {}

                for variable_elem in concept_elem.iter('variable'):
                    variables[variable_elem.attrib['name']] = variable_elem.text

                data[concept] = variables

        return data
开发者ID:danabauer,项目名称:census,代码行数:25,代码来源:core.py

示例10: download

def download(job, regex):
    """Grabs platform specific distribution targets from Hudson"""
    url = urllib.urlopen("/".join([HUDSON_ROOT, job, HUDSON_XML_SUFFIX]))
    hudson_xml = url.read()
    hudson_xml = hudson_xml.replace('origin/', 'origin_')
    url.close()
    root = XML(hudson_xml)

    building = root.findtext("./building")
    if building == 'true':
        print '%s build in progress, exiting...' % job
        sys.exit(1)
    revision = root.findtext("./changeSet/revision/revision")
    artifacts = root.findall("./artifact")
    print "Retrieving %s job artifacts from revision: %s" % (job, revision)
    base_url = "/".join([HUDSON_ROOT, job, 'lastSuccessfulBuild/artifact'])
    new_artifacts = list()
    for artifact in artifacts:
        filename = artifact.findtext("fileName")
        if not regex.match(filename):
            continue
        artifact_url = "/".join([base_url, artifact.findtext("relativePath")])
        print "Downloading %s from URL %s" % (filename, artifact_url)
        urllib.urlretrieve(artifact_url , filename)
        new_artifacts.append(filename)
    return [revision, new_artifacts]
开发者ID:DonaldMacDonald,项目名称:openmicroscopy,代码行数:26,代码来源:composite.py

示例11: findSha1Artifacts

	def findSha1Artifacts(self, strFileName, strGroupID, strArtifactID):
		atVersions = []

		# Generate the SHA1 sum for the file.
		strFileSha1 = self.generate_sha1_from_file(strFileName)

		strPath = self.strUrlLuceneSearchSha1 % strFileSha1
		aucContent = self.tRestDriver.get(self.tServerBaseUrl, strPath)
		tSearchResult = XML(aucContent)

		# The search result must be complete.
		if tSearchResult.findtext('tooManyResults')!='false':
			raise Exception("Received a truncated search result!")
	
		# Loop over all results.
		for tNode in tSearchResult.findall('data/artifact'):
			strG = tNode.findtext('groupId')
			strA = tNode.findtext('artifactId')
			strVersion = tNode.findtext('version')

			if isinstance(strG, basestring)==True and isinstance(strA, basestring)==True and isinstance(strVersion, basestring)==True:
				strG = strG.strip()
				strA = strA.strip()
				strVersion = strVersion.strip()
				if strGroupID==strG and strArtifactID==strA:
					if strVersion=='SNAPSHOT':
						tVersion = deploy_version.version(0, 0, 0)
					else:
						tVersion = deploy_version.version(strVersion)
					atVersions.append(tVersion)

		atVersions.sort()

		return atVersions
开发者ID:muhkuh-sys,项目名称:mbs,代码行数:34,代码来源:repository_driver_nexus.py

示例12: protocolParser

def protocolParser(protocol,game,conn):
   
    print protocol
    xmlelement=XML(protocol)
    print xmlelement.tag
    if(xmlelement.tag=="CLOGIN"):
        a_lst = xmlelement.findall("username")
        val=''
        for node in a_lst:
            val=node.attrib["usr"]
            print val
        threading.Thread(target=srvau(val,game,conn)).start()
        
    elif(xmlelement.tag=="CPLAY"):
        a_lst = xmlelement.findall("username")
        print 'a_lst'
        val=''
        for node in a_lst:
            val=node.attrib["usr"]
            print val
       
        threading.Thread(target=splay(val,game,conn)).start()
        
        
    elif(xmlelement.tag=="CDICE"):
       
        a_lst = xmlelement.findall("username")
        
        val=''
        for node in a_lst:
            val=node.attrib["usr"]
            print val
       
        threading.Thread(target=sdice(val,game,conn)).start()
开发者ID:sgokdeniz,项目名称:swe544Backgammon,代码行数:34,代码来源:__init__.py

示例13: updated

        def updated(downloader, path, _):
            if path is None:
                logging.error('internet archive file list get fail')
                # FIXME: report to user a failure to download
                return

            from xml.etree.ElementTree import XML
            xml = XML(open(path, 'r').read())
            os.remove(path)

            table = {
                'text pdf': u'application/pdf',
                'grayscale luratech pdf': u'application/pdf-bw',
                'image container pdf': u'application/pdf',
                'djvu': u'image/x.djvu',
                'epub': u'application/epub+zip',
            }

            chosen = None
            for element in xml.findall('file'):
                fmt = element.find('format').text.lower()
                if fmt in table:
                    if table[fmt] == content_type:
                        chosen = element.get('name')
                        break

            if chosen is None:
                logging.error('internet archive file list omits content type')
                # FIXME: report to user a failure to find matching content
                return

            url = os.path.join(url_base, chosen)
            GObject.idle_add(download_cb, url)
开发者ID:leonardcj,项目名称:get-books-activity,代码行数:33,代码来源:opds.py

示例14: fields

    def fields(self, year, flat=False):

        data = {}

        fields_url = DEFINITIONS[self.dataset].get(str(year))

        if not fields_url:
            raise CensusException('%s is not available for %s' % (self.dataset, year))

        resp = requests.get(fields_url)
        doc = XML(resp.text)

        if flat:

            for elem in doc.iter('variable'):
                data[elem.attrib['name']] = "%s: %s" % (elem.attrib['concept'], elem.text)

        else:

            for concept_elem in doc.iter('concept'):

                concept = concept_elem.attrib['name']
                variables = {}

                for variable_elem in concept_elem.iter('variable'):
                    variables[variable_elem.attrib['name']] = variable_elem.text

                data[concept] = variables

        return data
开发者ID:rdhyee,项目名称:census,代码行数:30,代码来源:core.py

示例15: _process_response

 def _process_response(self, response, returntype=dict):
   """ big ugly function.. slowly improving. """
   if DEBUG:
     print response
   # Parse XML
   root = XML(response)
   # Dict repsonse
   if returntype==dict:
       response_data = xmldict.XmlDictConfig(root)
       if response_data.has_key("error"):
           raise RemoteError(response_data)
   # List response
   elif returntype==list:
       response_data = []
       return_dict = {}
       for elem in root.getiterator():
           if elem.tag == root_tag and return_dict.has_key(elem.tag):
               response_data.append(return_dict)
               return_dict = {elem.tag: elem.text}
           else:
               return_dict[elem.tag] = elem.text
           if return_dict.has_key("error"):
               raise RemoteError(return_dict)
       # add final dict to the list
       response_data.append(return_dict)
   else:
       raise InvalidParameterError("unkown datatype: %s" % (returntype))
   if DEBUG:
     print response_data
   return response_data
开发者ID:GunioRobot,项目名称:python-viddler,代码行数:30,代码来源:viddler.py


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