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


Python ElementTree.fromstring方法代码示例

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


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

示例1: _init_datatable

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def _init_datatable(self):
        template = ElementTree.fromstring("""
          <vframe>
            <hframe>
              <QLineEdit id='filter' name='input_xlarge' placeholder='Filter'/>
              <stretch/><pushbutton text='Refresh' click='refresh_datatable'/>
            </hframe>
            <vframe id='table'/>
          </vframe>""")
        # Build the datatable
        self.datatable_wrap = PKWidget(template, self)
        datatable = QtWidgets.QTableWidget(0, 3, parent=None)
        datatable.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
        datatable.setHorizontalHeaderLabels(['Variable', 'Value', 'Type   '])
        datatable.horizontalHeader().setSectionResizeMode(0, QtWidgets.QHeaderView.Interactive)
        datatable.horizontalHeader().setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
        datatable.horizontalHeader().setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
        datatable.horizontalHeader().resizeSection(0, 200)
        datatable.verticalHeader().setVisible(False)
        datatable.verticalHeader().setDefaultSectionSize(19)
        datatable.setParent(self.datatable_wrap)
        self.datatable_wrap.manifest.table.layout().addWidget(datatable)
        # Connect the filter input
        self.datatable_wrap.manifest.filter.textChanged.connect(self.filter_datatable)
        return datatable 
开发者ID:pkkid,项目名称:pkmeter,代码行数:27,代码来源:pkconfig.py

示例2: _retrieve_deploy_result

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def _retrieve_deploy_result(self, async_process_id):
        """ Retrieves status for specified deployment id """
        attributes = {
            'client': 'Metahelper',
            'sessionId': self._session.get_session_id(),
            'asyncProcessId': async_process_id,
            'includeDetails': 'true'
            }
        mt_request = msg.CHECK_DEPLOY_STATUS_MSG.format(**attributes)
        headers = {'Content-type': 'text/xml', 'SOAPAction': 'checkDeployStatus'}
        res = self._session.post(self._get_api_url(), headers=headers, data=mt_request)
        root = ET.fromstring(res.text)
        result = root.find(
            'soapenv:Body/mt:checkDeployStatusResponse/mt:result',
            self._XML_NAMESPACES)
        if result is None:
            raise Exception("Result node could not be found: %s" % res.text)

        return result 
开发者ID:rbauction,项目名称:sfdclib,代码行数:21,代码来源:metadata.py

示例3: _retrieve_retrieve_result

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def _retrieve_retrieve_result(self, async_process_id, include_zip):
        """ Retrieves status for specified retrieval id """
        attributes = {
            'client': 'Metahelper',
            'sessionId': self._session.get_session_id(),
            'asyncProcessId': async_process_id,
            'includeZip': include_zip
        }
        mt_request = msg.CHECK_RETRIEVE_STATUS_MSG.format(**attributes)
        headers = {'Content-type': 'text/xml', 'SOAPAction': 'checkRetrieveStatus'}
        res = self._session.post(self._get_api_url(), headers=headers, data=mt_request)
        root = ET.fromstring(res.text)
        result = root.find(
            'soapenv:Body/mt:checkRetrieveStatusResponse/mt:result',
            self._XML_NAMESPACES)
        if result is None:
            raise Exception("Result node could not be found: %s" % res.text)

        return result 
开发者ID:rbauction,项目名称:sfdclib,代码行数:21,代码来源:metadata.py

示例4: login

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def login(self):
        url = self.construct_url(self.get_soap_api_uri())
        headers = {'Content-Type': 'text/xml', 'SOAPAction': 'login'}
        password = self._password
        if self._token:
            password += self._token
        data = SfdcSession._LOGIN_TMPL.format(**{'username': self._username, 'password': password})
        r = self.post(url, headers=headers, data=data)
        root = ET.fromstring(r.text)
        if root.find('soapenv:Body/soapenv:Fault', SfdcSession._XML_NAMESPACES):
            raise Exception("Could not log in. Code: %s Message: %s" % (
                root.find('soapenv:Body/soapenv:Fault/faultcode', SfdcSession._XML_NAMESPACES).text,
                root.find('soapenv:Body/soapenv:Fault/faultstring', SfdcSession._XML_NAMESPACES).text))
        self._session_id = root.find('soapenv:Body/d:loginResponse/d:result/d:sessionId', SfdcSession._XML_NAMESPACES).text
        server_url = root.find('soapenv:Body/d:loginResponse/d:result/d:serverUrl', SfdcSession._XML_NAMESPACES).text
        self._instance = re.search("""https://(.*).salesforce.com/.*""", server_url).group(1) 
开发者ID:rbauction,项目名称:sfdclib,代码行数:18,代码来源:session.py

示例5: from_xml

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def from_xml(data):
    '''
    Convert XML to ElementTree.Element

    Parameters
    ----------
    data : string
        The XML to parse

    Returns
    -------
    :class:`ElementTree.Element`

    '''
    try:
        return ET.fromstring(data)
    except:
        for i, line in enumerate(data.split('\n')):
            print(i+1, line)
        raise 
开发者ID:sassoftware,项目名称:python-esppy,代码行数:22,代码来源:xml.py

示例6: message

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def message(self,message):
        if self.isHandshakeComplete == False:
            Connection.message(self,message)
            return

        #logging.info("MSG: " + message)

        xml = None
        o = None

        for c in message:
            if c == '{' or c == '[':
                o = json.loads(str(message))
                break
            elif c == '<':
                xml = ElementTree.fromstring(str(message))
                break

        if o != None:
            self.processJson(o)
        elif xml != None:
            self.processXml(xml) 
开发者ID:sassoftware,项目名称:python-esppy,代码行数:24,代码来源:connections.py

示例7: from_xml

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def from_xml(cls, data, session=None):
        '''
        Create schema field from XML definition

        Parameters
        ----------
        data : xml-string or ElementTree.Element
            The schema field XML definition
        session : requests.Session
            The ESP session object

        Returns
        -------
        :class:`SchemaField`

        '''
        out = cls('', type='double', key=False)
        out.session = session

        if isinstance(data, six.string_types):
            data = ET.fromstring(data)

        out._set_attributes(data.attrib)

        return out 
开发者ID:sassoftware,项目名称:python-esppy,代码行数:27,代码来源:schema.py

示例8: __init__

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def __init__(self, etree):
        r"""
        Initialize a new Element wrapper for ``etree``.

        If ``etree`` is a string, then it will be converted to an
        Element object using ``ElementTree.fromstring()`` first:

            >>> ElementWrapper("<test></test>")
            <Element "<?xml version='1.0' encoding='utf8'?>\n<test />">

        """
        if isinstance(etree, compat.string_types):
            etree = ElementTree.fromstring(etree)
        self.__dict__['_etree'] = etree 
开发者ID:rafasashi,项目名称:razzy-spinner,代码行数:16,代码来源:internals.py

示例9: _extract_response_xml

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def _extract_response_xml(self, domain, response):
        """Extract XML content of an HTTP response into dictionary format.

        Args:
            response: HTML Response objects
        Returns:
            A dictionary: {alexa-ranking key : alexa-ranking value}.
        """
        attributes = {}
        alexa_keys = {'POPULARITY': 'TEXT', 'REACH': 'RANK', 'RANK': 'DELTA'}
        try:
            xml_root = ET.fromstring(response._content)
            for xml_child in xml_root.findall('SD//'):
                if xml_child.tag in alexa_keys and \
                        alexa_keys[xml_child.tag] in xml_child.attrib:
                    attributes[xml_child.tag.lower(
                    )] = xml_child.attrib[alexa_keys[xml_child.tag]]
        except ParseError:
            # Skip ill-formatted XML and return no Alexa attributes
            pass
        attributes['domain'] = domain
        return {'attributes': attributes} 
开发者ID:Yelp,项目名称:threat_intel,代码行数:24,代码来源:alexaranking.py

示例10: channellist

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def channellist(self,clist):
        root = ET.fromstring(self.xmldata)
        services = root[0][0].findall("{urn:dvb:ipisdns:2006}SingleService")
        for i in services:
            channelid = i[1].attrib["ServiceName"]
            clist[channelid] = {}
            #clist[channelid]["logo"] = i[1].attrib["logoURI"]
            url = "http://172.26.22.23:2001/appclient/incoming/epg/MAY_1/imSer/"+channelid+".jpg"
            clist[channelid]["logo"] = url
            clist[channelid]["address"] = i[0][0].attrib["Address"]
            clist[channelid]["port"] = i[0][0].attrib["Port"]
            clist[channelid]["name"] = i[2][0].text
            clist[channelid]["shortname"] = i[2][1].text
            clist[channelid]["desc"] = i[2][2].text
            clist[channelid]["tags"] = i[2][3][0].text.split("/")
        return clist 
开发者ID:ese,项目名称:movistartv2xmltv,代码行数:18,代码来源:tva.py

示例11: search

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def search(name, complete=False):
    from kmediatorrent.caching import shelf
    import hashlib
    search_hash = hashlib.sha1(name).hexdigest()
    with shelf("com.thetvdb.search.%s" % search_hash) as show:
        if not show:
            import re
            import xml.etree.ElementTree as ET
            from kmediatorrent.utils import url_get
            dom = ET.fromstring(url_get("%s/api/GetSeries.php" % BASE_URL, params={
                "seriesname": name,
            }, headers=HEADERS, with_immunicity=False))
            if not len(dom):
                return
            meta = dom2dict(dom[0])
            if not complete:
                return update_image_urls(meta)
            show.update(get(meta["id"]))
        return show 
开发者ID:jmarth,项目名称:plugin.video.kmediatorrent,代码行数:21,代码来源:tvdb.py

示例12: get_all_meta

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def get_all_meta(show_id):
    import xml.etree.ElementTree as ET
    from concurrent import futures
    from kmediatorrent.utils import url_get, joining

    def _get_all_meta():
        r = url_get("%s/all/%s.xml" % (show_base_url(show_id), LANG), headers=HEADERS, with_immunicity=False)
        dom = ET.fromstring(r)
        if not len(dom):
            return
        return update_image_urls(dom2dict(dom))
    with futures.ThreadPoolExecutor(max_workers=2) as pool:
        meta = pool.submit(_get_all_meta)
        banners = pool.submit(get_banners, show_id)
    meta = meta.result()
    meta["series"][0]["episodes"] = meta["episode"]
    meta = meta["series"][0]
    meta["banners"] = banners.result() or []
    return meta 
开发者ID:jmarth,项目名称:plugin.video.kmediatorrent,代码行数:21,代码来源:tvdb.py

示例13: addOSMFromXML

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def addOSMFromXML(course_json, xml_data, options_dict={}, printf=print):
    printf("Adding OpenStreetMap from XML")
    op = overpy.Overpass()
    result = op.parse_xml(xml_data)

    printf("Determining the UTM Geo Projection for this area")
    # Find the lat and lon bounding box from the XML directly
    # Can't find the query bounds in overpy
    root = ET.fromstring(xml_data)
    for bounds in root.iter('bounds'):
        latmin = float(bounds.get('minlat'))
        latmax = float(bounds.get('maxlat'))
        lonmin = float(bounds.get('minlon'))
        lonmax = float(bounds.get('maxlon'))
        break
    
    # Create a basic geopointcloud to handle this projection
    pc = GeoPointCloud()
    pc.addFromLatLon((latmin, lonmin), (latmax, lonmax), printf=printf)

    trees = addOSMToTGC(course_json, pc, result, x_offset=float(options_dict.get('adjust_ew', 0.0)), y_offset=float(options_dict.get('adjust_ns', 0.0)), \
                options_dict=options_dict, printf=printf)

    return course_json, trees 
开发者ID:chadrockey,项目名称:TGC-Designer-Tools,代码行数:26,代码来源:OSMTGC.py

示例14: xmlread

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def xmlread(filename):
    global _xml_path_zip
    global _xml_zfile
    path = filename
    pos_at = path.index('@')
    if pos_at == -1:
        print("character '@' is not found from the given path '%s'"%(path))
        assert 0
    path_zip = path[0: pos_at]
    path_xml = path[pos_at + 2:]
    if not os.path.isfile(path_zip):
        print("zip file '%s' is not found"%(path_zip))
        assert 0
    for i in xrange(len(_xml_path_zip)):
        if _xml_path_zip[i] == path_zip:
            data = _xml_zfile[i].open(path_xml)
            return ET.fromstring(data.read())
    _xml_path_zip.append(path_zip)
    print("read new xml file '%s'"%(path_zip))
    _xml_zfile.append(zipfile.ZipFile(path_zip, 'r'))
    data = _xml_zfile[-1].open(path_xml)
    return ET.fromstring(data.read()) 
开发者ID:facebookresearch,项目名称:PoseWarper,代码行数:24,代码来源:zipreader.py

示例15: __init__

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstring [as 别名]
def __init__(self, device, prefix="", ignore_dup_errors=True):
        # Create a class logger
        self._logger = getlogger(__name__ + "." + self.__class__.__name__)
        self.device = device
        self.prefix = prefix
        self.ignore_dup_errors = ignore_dup_errors

        # Build the initial uid-message
        self._uidmessage = ET.fromstring("<uid-message>" +
                                         "<version>1.0</version>" +
                                         "<type>update</type>" +
                                         "<payload/>" +
                                         "</uid-message>")
        # Batch state
        self._batch = False
        self._batch_uidmessage = deepcopy(self._uidmessage) 
开发者ID:PaloAltoNetworks,项目名称:terraform-templates,代码行数:18,代码来源:userid.py


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