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


Python etree.QName方法代码示例

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


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

示例1: _qname

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def _qname(self, name, default_ns=None):
        """Make a name into a QName.

        Helper method to :meth:`_get_nodes`.

        Args:
          name (str): Name, either prefixed 'foo:bar' or unprefixed 'bar'.
          default_ns (str): Namespace to use if no prefix given.
        Returns:
          lxml.etree.QName
        """
        if ':' in name:
            pfx, localname = name.split(':', 1)
            ns = self.nsmap.get(pfx)
            if not ns:
                raise ValueError("Unknown namespace prefix '{0}'!".format(pfx))
            return QName(ns, localname)
        else:
            return QName(default_ns, name) 
开发者ID:CiscoTestAutomation,项目名称:genielibs,代码行数:21,代码来源:rpcbuilder.py

示例2: _qname

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def _qname(self, name):
        """Convert name to an XML QName

        e.g. pdf:Producer -> {http://ns.adobe.com/pdf/1.3/}Producer
        """
        if isinstance(name, QName):
            return name
        if not isinstance(name, str):
            raise TypeError("{} must be str".format(name))
        if name == '':
            return name
        if name.startswith('{'):
            return name
        prefix, tag = name.split(':', maxsplit=1)
        uri = self.NS[prefix]
        return QName(uri, tag) 
开发者ID:pikepdf,项目名称:pikepdf,代码行数:18,代码来源:metadata.py

示例3: pdfa_status

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def pdfa_status(self):
        """Returns the PDF/A conformance level claimed by this PDF, or False

        A PDF may claim to PDF/A compliant without this being true. Use an
        independent verifier such as veraPDF to test if a PDF is truly
        conformant.

        Returns:
            str: The conformance level of the PDF/A, or an empty string if the
            PDF does not claim PDF/A conformance. Possible valid values
            are: 1A, 1B, 2A, 2B, 2U, 3A, 3B, 3U.
        """
        key_part = QName(XMP_NS_PDFA_ID, 'part')
        key_conformance = QName(XMP_NS_PDFA_ID, 'conformance')
        try:
            return self[key_part] + self[key_conformance]
        except KeyError:
            return '' 
开发者ID:pikepdf,项目名称:pikepdf,代码行数:20,代码来源:metadata.py

示例4: pdfx_status

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def pdfx_status(self):
        """Returns the PDF/X conformance level claimed by this PDF, or False

        A PDF may claim to PDF/X compliant without this being true. Use an
        independent verifier such as veraPDF to test if a PDF is truly
        conformant.

        Returns:
            str: The conformance level of the PDF/X, or an empty string if the
            PDF does not claim PDF/X conformance.
        """
        pdfx_version = QName(XMP_NS_PDFX_ID, 'GTS_PDFXVersion')
        try:
            return self[pdfx_version]
        except KeyError:
            return '' 
开发者ID:pikepdf,项目名称:pikepdf,代码行数:18,代码来源:metadata.py

示例5: to_et

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def to_et(self, tag):
        def convert(v):
            if isinstance(v, _Base):
                return v.to_et(e.name)
            elif isinstance(v, objectify.ObjectifiedElement):
                assert ET.QName(v.tag).localname == itag
                return v
            return self._M(itag, v)

        args = []
        for e in self._ELEMENTS:
            itag = e.name
            k = _pythonify(itag)
            v = getattr(self, k)
            if v is None:
                continue
            if isinstance(v, list):
                assert e.is_list
                ele = list(map(convert, v))
            else:
                assert not e.is_list
                ele = [convert(v)]
            args.extend(ele)
        return self._M(tag, *args) 
开发者ID:OpenState-SDN,项目名称:ryu,代码行数:26,代码来源:base.py

示例6: list_bucket

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def list_bucket(bucket):
    remain = ['']
    while remain:
        prefix = remain.pop()
        params = urllib.urlencode({"delimiter": "/", "prefix":prefix})
        req = 'http://%s.s3.amazonaws.com/?%s' % (bucket, params)
        doc = etree.parse(urlopen(req))
        for element in doc.iter():
            tag = etree.QName(element).localname
            if tag == 'Prefix' and element.text is not None and element.text != prefix:
                remain.append(element.text)
            elif tag == 'Contents':
                result = S3Object()
                for child in element:
                    child_tag = etree.QName(child).localname
                    if child_tag == 'Key':
                        result.key = child.text
                    elif child_tag == 'ETag':
                        result.hash = child.text.strip('"')
                    elif child_tag == 'Size':
                        result.size = int(child.text)
                    elif child_tag == 'LastModified':
                        result.date = calendar.timegm(time.strptime(child.text, '%Y-%m-%dT%H:%M:%S.000Z'))
                result.check()
                yield result 
开发者ID:MozillaSecurity,项目名称:peach,代码行数:27,代码来源:userdata.py

示例7: serialize

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def serialize(self, sink: Union[IO, str], cas: Cas, pretty_print=True):
        xmi_attrs = {"{http://www.omg.org/XMI}version": "2.0"}

        root = etree.Element(etree.QName(self._nsmap["xmi"], "XMI"), nsmap=self._nsmap, **xmi_attrs)

        self._serialize_cas_null(root)

        # Find all fs, even the ones that are not directly added to a sofa
        for fs in sorted(cas._find_all_fs(), key=lambda a: a.xmiID):
            self._serialize_feature_structure(cas, root, fs)

        for sofa in cas.sofas:
            self._serialize_sofa(root, sofa)

        for view in cas.views:
            self._serialize_view(root, view)

        doc = etree.ElementTree(root)
        etree.cleanup_namespaces(doc, top_nsmap=self._nsmap)

        doc.write(sink, xml_declaration=True, pretty_print=pretty_print) 
开发者ID:dkpro,项目名称:dkpro-cassis,代码行数:23,代码来源:xmi.py

示例8: unmarshal_atom_feed

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def unmarshal_atom_feed(cls, feedelem, resp):
        """Factory method producing a Feed object from a parsed ElementTree

        :param feedelem: Parsed ElementTree object representing an atom feed.
        :param resp: The Response from which this Feed was parsed.
        :return: a new Feed object representing the feedelem parameter.
        """
        ret = cls({}, [])
        for child in list(feedelem):
            if child.tag == str(etree.QName(const.ATOM_NS, 'entry')):
                # NB: The use of ret.self_link here relies on <entry>s being
                # AFTER the self link in the <feed>.  (They are in fact last.)
                ret.entries.append(Entry.unmarshal_atom_entry(child, resp))
            elif not list(child):
                cls._process_props(child, ret.properties)
        return ret 
开发者ID:powervm,项目名称:pypowervm,代码行数:18,代码来源:entities.py

示例9: unmarshal_atom_entry

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def unmarshal_atom_entry(cls, entryelem, resp):
        """Factory method producing an Entry object from a parsed ElementTree

        :param entryelem: Parsed ElementTree object representing an atom entry.
        :param resp: The Response containing (the feed containing) the entry.
        :return: a new Entry object representing the entryelem parameter.
        """
        entryprops = {}
        element = None
        for child in list(entryelem):
            if child.tag == str(etree.QName(const.ATOM_NS, 'content')):
                # PowerVM API only has one element per entry
                element = child[0]
            elif not list(child):
                cls._process_props(child, entryprops)
        return cls(entryprops, element, resp.adapter) 
开发者ID:powervm,项目名称:pypowervm,代码行数:18,代码来源:entities.py

示例10: parse_key

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def parse_key(self, elem):
        """SeriesKey, GroupKey, observation dimensions."""
        cls = {
            'GroupKey': GroupKey,
            'ObsKey': Key,
            'SeriesKey': SeriesKey,
            'Key': DataKey,  # for DataKeySet
            }[QName(elem).localname]
        if cls is not DataKey:
            # Most data: the value is specified as an XML attribute
            kv = {e.attrib['id']: e.attrib['value'] for e in
                  elem.iterchildren()}

            return cls(**kv, dsd=self._get_current(DataStructureDefinition))
        else:
            # <str:DataKeySet> and <str:CubeRegion>: the value(s) are specified
            # with a <com:Value>...</com:Value> element.
            kvs = {}
            for e in elem.iterchildren():
                c = self._get_cc_dsd().dimensions.get(e.attrib['id'])
                kvs[c] = ComponentValue(value_for=c,
                                        value=self._parse(e)['value'])
            return cls(included=elem.attrib.get('isIncluded', True),
                       key_value=kvs) 
开发者ID:dr-leo,项目名称:pandaSDMX,代码行数:26,代码来源:sdmxml.py

示例11: parse_componentlist

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def parse_componentlist(self, elem):
        attr = copy(elem.attrib)

        # Determine the class
        try:
            cls_name = attr.pop('id')
        except KeyError:
            # SDMX-ML spec for, e.g. DimensionList: "The id attribute is
            # provided in this case for completeness. However, its value is
            # fixed to 'DimensionDescriptor'."
            cls_name = QName(elem).localname.replace('List', 'Descriptor')
        finally:
            ComponentListClass = getattr(pandasdmx.model, cls_name)

        cl = ComponentListClass(
            components=list(chain(*self._parse(elem, unwrap=False).values())),
            **attr,
        )

        try:
            cl.assign_order()
        except AttributeError:
            pass

        return cl 
开发者ID:dr-leo,项目名称:pandaSDMX,代码行数:27,代码来源:sdmxml.py

示例12: parse_memberselection

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def parse_memberselection(self, elem):
        """<com:KeyValue> (not inside <com:Key>); or <com:Attribute>."""
        values = self._parse(elem)
        values = list(map(lambda v: MemberValue(value=v), values['value']))

        # Values are for either a Dimension or Attribute, based on tag name
        kind = {
            'KeyValue': ('dimensions', Dimension),
            'Attribute': ('attributes', DataAttribute),
        }.get(QName(elem).localname)

        try:
            # Navigate from the current ContentConstraint to a
            # ConstrainableArtefact. If this is a DataFlow, it has a DSD.
            dsd = self._get_cc_dsd()
        except AttributeError:
            # Failed because the ContentConstraint is attached to something,
            # e.g. DataProvider, that does not provide an association to a DSD.
            # Try to get a Component from the current scope with matching ID.
            component = self._get_current(cls=kind[1], id=elem.attrib['id'])
        else:
            # Get the Component from the correct list according to the kind
            component = getattr(dsd, kind[0]).get(elem.attrib['id'])

        return MemberSelection(values=values, values_for=component) 
开发者ID:dr-leo,项目名称:pandaSDMX,代码行数:27,代码来源:sdmxml.py

示例13: get_pathway_info

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def get_pathway_info(self, identifier):
        """Sends a GET request. Returns pathway metadata as dict.
        Args:
          identifier (str): WikiPathways ID.
        """

        request_params = {'pwId' : identifier}
        response = requests.get(self.base_iri + 'getPathwayInfo', params=request_params)
        dom = ET.fromstring(response.text)

        pathway_using_api_terms = {}
        for node in dom.findall('ns1:pathwayInfo', self.NAMESPACES):
            for attribute in node:
                pathway_using_api_terms[ET.QName(attribute).localname] = attribute.text
        pathway = self.__convert_api_terms_to_standard_terms(pathway_using_api_terms)
        pathway = self.__enrich_pathway(pathway)

        return pathway 
开发者ID:nsalomonis,项目名称:altanalyze,代码行数:20,代码来源:wikipathways_api_client.py

示例14: _details_do_merge

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def _details_do_merge(details, root):
    # Merge the remaining details into the composite document.
    for namespace in sorted(details):
        xmldata = details[namespace]
        if xmldata is not None:
            try:
                detail = etree.fromstring(xmldata)
            except etree.XMLSyntaxError as e:
                maaslog.warning("Invalid %s details: %s", namespace, e)
            else:
                # Add the namespace to all unqualified elements.
                for elem in detail.iter("{}*"):
                    elem.tag = etree.QName(namespace, elem.tag)
                root.append(detail)

    # Re-home `root` in a new tree. This ensures that XPath
    # expressions like "/some-tag" work correctly. Without this, when
    # there's well-formed lshw data -- see the backward-compatibilty
    # hack futher up -- expressions would be evaluated from the first
    # root created in this function, even though that root is now the
    # parent of the current `root`.
    return etree.ElementTree(root) 
开发者ID:maas,项目名称:maas,代码行数:24,代码来源:tags.py

示例15: temp_context

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import QName [as 别名]
def temp_context(self, instance):
        tree = etree.parse(openurl(instance))
        defs = defaultdict(dict)
        for x in tree.iter():
            if 'id' in x.attrib:
                for xx in x.iterdescendants():
                    if xx.text and xx.text.strip() and \
                                'identifier' not in str(xx.tag):
                        key = etree.QName(xx.tag).localname.strip()
                        try:
                            possible_dt = xx.text.strip()[:10]
                            val = datetime.datetime.strptime(possible_dt, 
                                                             '%Y-%m-%d').date()
                        except ValueError:
                            val = xx.text.split(':')[-1].strip()
                        defs[x.attrib['id'].strip()][key] = val
                        if xx.attrib and xx.attrib.keys() != ['scheme']:
                            for row in xx.attrib.items():
                                key = row[1].split(':')[-1].strip()
                                val = xx.text.split(':')[-1].strip()
                                defs[x.attrib['id'].strip()][key] = val
        return tree, defs 
开发者ID:marisj,项目名称:financials,代码行数:24,代码来源:xbrl.py


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