How to use the lxml.etree.QName function in lxml

To help you get started, we’ve selected a few lxml examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mvantellingen / python-zeep / tests / test_xsd_indicators_sequence.py View on Github external
xsd.ComplexType(
            xsd.Sequence(
                [
                    xsd.Element(
                        etree.QName("http://tests.python-zeep.org/", "item_1"),
                        xsd.String(),
                    ),
                    xsd.Element(
                        etree.QName("http://tests.python-zeep.org/", "item_2"),
                        xsd.String(),
                    ),
                ]
            ),
            [
                xsd.Attribute(
                    etree.QName("http://tests.python-zeep.org/", "attr_1"), xsd.String()
                ),
                xsd.Attribute("attr_2", xsd.String()),
            ],
        ),
    )
    expected = load_xml(
        """
        
          foo
          bar
        
    """
    )
    obj = custom_element.parse(expected, None)
    assert obj.item_1 == "foo"
    assert obj.item_2 == "bar"
github mvantellingen / python-zeep / tests / test_xsd_signatures.py View on Github external
def test_signature_complex_type_sequence_with_anys():
    custom_type = xsd.Element(
        etree.QName("http://tests.python-zeep.org/", "authentication"),
        xsd.ComplexType(
            xsd.Choice(
                [
                    xsd.Element(
                        etree.QName("http://tests.python-zeep.org/", "item_1"),
                        xsd.String(),
                    ),
                    xsd.Element(
                        etree.QName("http://tests.python-zeep.org/", "item_2"),
                        xsd.ComplexType(xsd.Sequence([xsd.Any(), xsd.Any()])),
                    ),
                ]
            )
        ),
    )
    assert custom_type.signature() == (
        "{http://tests.python-zeep.org/}authentication("
        + "({item_1: xsd:string} | {item_2: {_value_1: ANY, _value_2: ANY}})"
        + ")"
    )
github Azure / sonic-buildimage / src / sonic-config-engine / minigraph.py View on Github external
if hostname.lower() == hname.lower():
                    myasn = asn
                    peers = router.find(str(QName(ns1, "Peers")))
                    for bgpPeer in peers.findall(str(QName(ns, "BGPPeer"))):
                        addr = bgpPeer.find(str(QName(ns, "Address"))).text
                        if bgpPeer.find(str(QName(ns1, "PeersRange"))) is not None: # FIXME: is better to check for type BGPPeerPassive
                            name = bgpPeer.find(str(QName(ns1, "Name"))).text
                            ip_range = bgpPeer.find(str(QName(ns1, "PeersRange"))).text
                            ip_range_group = ip_range.split(';') if ip_range and ip_range != "" else []
                            bgp_peers_with_range[name] = {
                                'name': name,
                                'ip_range': ip_range_group
                            }
                            if bgpPeer.find(str(QName(ns, "Address"))) is not None:
                                bgp_peers_with_range[name]['src_address'] = bgpPeer.find(str(QName(ns, "Address"))).text
                            if bgpPeer.find(str(QName(ns1, "PeerAsn"))) is not None:
                                bgp_peers_with_range[name]['peer_asn'] = bgpPeer.find(str(QName(ns1, "PeerAsn"))).text
                else:
                    for peer in bgp_sessions:
                        bgp_session = bgp_sessions[peer]
                        if hostname.lower() == bgp_session['name'].lower():
                            bgp_session['asn'] = asn

    bgp_monitors = { key: bgp_sessions[key] for key in bgp_sessions if bgp_sessions[key].has_key('asn') and bgp_sessions[key]['name'] == 'BGPMonitor' }
    bgp_sessions = { key: bgp_sessions[key] for key in bgp_sessions if bgp_sessions[key].has_key('asn') and int(bgp_sessions[key]['asn']) != 0 }

    return bgp_sessions, myasn, bgp_peers_with_range, bgp_monitors
github mvantellingen / python-zeep / src / zeep / xsd / schema.py View on Github external
:rtype: lxml.etree.QNaame

        """
        if isinstance(name, etree.QName):
            return name

        if not name.startswith("{") and ":" in name and self._prefix_map_auto:
            prefix, localname = name.split(":", 1)
            if prefix in self._prefix_map_custom:
                return etree.QName(self._prefix_map_custom[prefix], localname)
            elif prefix in self._prefix_map_auto:
                return etree.QName(self._prefix_map_auto[prefix], localname)
            else:
                raise ValueError("No namespace defined for the prefix %r" % prefix)
        else:
            return etree.QName(name)
github pikepdf / pikepdf / src / pikepdf / models / metadata.py View on Github external
def _update_docinfo(self):
        """Update the PDF's DocumentInfo dictionary to match XMP metadata

        The standard mapping is described here:
            https://www.pdfa.org/pdfa-metadata-xmp-rdf-dublin-core/
        """
        self._pdf.docinfo  # Touch object to ensure it exists
        for uri, element, docinfo_name, converter in self.DOCINFO_MAPPING:
            qname = QName(uri, element)
            try:
                value = self[qname]
            except KeyError:
                if docinfo_name in self._pdf.docinfo:
                    del self._pdf.docinfo[docinfo_name]
                continue
            if converter:
                try:
                    value = converter.docinfo_from_xmp(value)
                except ValueError:
                    warn(
                        "The DocumentInfo field {} could not be updated from XMP".format(
                            docinfo_name
                        )
                    )
                    value = None
github mvantellingen / python-zeep / src / zeep / helpers.py View on Github external
def create_xml_soap_map(values):
    """Create an http://xml.apache.org/xml-soap#Map value."""
    Map = xsd.ComplexType(
        xsd.Sequence(
            [xsd.Element("item", xsd.AnyType(), min_occurs=1, max_occurs="unbounded")]
        ),
        qname=etree.QName("{http://xml.apache.org/xml-soap}Map"),
    )

    KeyValueData = xsd.Element(
        "{http://xml.apache.org/xml-soap}KeyValueData",
        xsd.ComplexType(
            xsd.Sequence(
                [xsd.Element("key", xsd.AnyType()), xsd.Element("value", xsd.AnyType())]
            )
        ),
    )

    return Map(
        item=[
            KeyValueData(
                xsd.AnyObject(xsd.String(), key),
                xsd.AnyObject(guess_xsd_type(value), value),
github KBNLresearch / omSipCreator / omSipCreator / premis.py View on Github external
def addAgent(softwareName):

    """Generate agent instance for creation software"""
    # TODO: do we need this function?

    # Create PREMIS event
    eventName = etree.QName(config.premis_ns, "event")
    event = etree.Element(eventName, nsmap=config.NSMAP)

    # Create PREMIS agent instance
    agentName = etree.QName(config.premis_ns, "agent")
    agent = etree.Element(agentName, nsmap=config.NSMAP)
    agent = etree.SubElement(event, "{%s}agent" % (config.premis_ns))
    agentIdentifier = etree.SubElement(
        agent, "{%s}agentIdentifier" % (config.premis_ns))
    agentIdentifierType = etree.SubElement(
        agentIdentifier, "{%s}agentIdentifierType" % (config.premis_ns))
    agentIdentifierType.text = "URI"

    # Values of agentIdentifierValue and agentName are set further below
    agentIdentifierValue = etree.SubElement(
        agentIdentifier, "{%s}agentIdentifierValue" % (config.premis_ns))
    agentName = etree.SubElement(agent, "{%s}agentName" % (config.premis_ns))
    agentType = etree.SubElement(agent, "{%s}agentType" % (config.premis_ns))
    agentType.text = "software"

    if softwareName == "isobuster":
github dkpro / dkpro-cassis / cassis / xmi.py View on Github external
def _serialize_sofa(self, root: etree.Element, sofa: Sofa):
        name = etree.QName(self._nsmap["cas"], "Sofa")
        elem = etree.SubElement(root, name)

        elem.attrib["{http://www.omg.org/XMI}id"] = str(sofa.xmiID)
        elem.attrib["sofaNum"] = str(sofa.sofaNum)
        elem.attrib["sofaID"] = str(sofa.sofaID)
        elem.attrib["mimeType"] = str(sofa.mimeType)
        elem.attrib["sofaString"] = str(sofa.sofaString)
github mitshel / sopds / book_tools / format / epub.py View on Github external
def __add_encryption_section(self, index, root, uri, content_id):
        # See http://www.marlin-community.com/files/marlin-EPUB-extension-v1.0.pdf
        # section 4.2.1
        key_name = EPub.CONTENT_ID_PREFIX + content_id

        enc_data = etree.SubElement(root, etree.QName(EPub.Namespace.ENCRYPTION, 'EncryptedData'), Id='ED%d' % index)
        etree.SubElement(enc_data, etree.QName(EPub.Namespace.ENCRYPTION, 'EncryptionMethod'), Algorithm=EPub.Namespace.ENCRYPTION + 'aes128-cbc')
        key_info = etree.SubElement(enc_data, etree.QName(EPub.Namespace.DIGITAL_SIGNATURE, 'KeyInfo'))
        key_name_tag = etree.SubElement(key_info, etree.QName(EPub.Namespace.DIGITAL_SIGNATURE, 'KeyName'))
        key_name_tag.text = key_name
        cipher_data = etree.SubElement(enc_data, etree.QName(EPub.Namespace.ENCRYPTION, 'CipherData'))
        etree.SubElement(cipher_data, etree.QName(EPub.Namespace.ENCRYPTION, 'CipherReference'), URI=uri)
github powervm / pypowervm / pypowervm / adapter.py View on Github external
:return: A message indicating the reason for the error, or None if no
                 error occurred.
        """
        err_reason = None
        root = None
        try:
            root = etree.fromstring(self.body)
        except Exception as e:
            err_reason = (_('Error parsing XML response from PowerVM: '
                            '%s') % str(e))
        if root is not None and root.tag == str(
                etree.QName(c.ATOM_NS, 'feed')):
            self.feed = ent.Feed.unmarshal_atom_feed(root, self)
        elif root is not None and root.tag == str(
                etree.QName(c.ATOM_NS, 'entry')):
            self.entry = ent.Entry.unmarshal_atom_entry(root, self)
        elif root is not None and '/Debug/' in self.reqpath:
            # Special case for Debug URIs - caller is expected to make use
            # of self.body only, and understand how it's formatted.
            pass
        elif err_reason is None:
            err_reason = _('Response is not an Atom feed/entry')

        return err_reason