我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用lxml.etree.QName()。
def _parse(self): # Is this the last pull request end_of_sequence = self._root.xpath("/s:Envelope/s:Body/wsen:PullResponse/wsen:EndOfSequence", namespaces=self._nsmap) self._end_of_sequence = bool(end_of_sequence) path = "/s:Envelope/s:Body/wsen:PullResponse/wsen:Items/dcim_class:{}".format(self._dcim_class) items = self._root.xpath(path, namespaces=self._nsmap) if not items: self._logger.debug("XPath '%s' with map '%s' found no items for doc:\n%s", path, self._nsmap, self._document) self._items = [] for item in items: item_dict = {} for element in item.getchildren(): tag = etree.QName(element.tag) item_dict[tag.localname] = element.text self._items.append(item_dict)
def test_subtransformation(): subtransformation = Transformation( Rule('*', lib.set_localname('pablo')) ) transformation = Transformation( lib.f(id, Ref('root')), lib.put_variable('source_id'), subtransformation, lib.f(id, Ref('root')), lib.put_variable('result_id'), lib.debug_symbols('source_id', 'result_id'), Rule(Not(If(Ref('source_id'), operator.eq, Ref('result_id'))), (lib.debug_message('NO!'), lib.debug_symbols('root'), lib.set_localname('neruda'), AbortRule)) ) doc = etree.fromstring('<augustus />') assert etree.QName(doc).text == 'augustus' result = transformation(doc) assert result.tag == 'pablo'
def equal_subtree(element, other_element, ignore_whitespaces=False): def compare_text(text, other_text): if ignore_whitespaces: if text is None: text = '' text = text.strip() if other_text is None: other_text = '' other_text = other_text.strip() return text == other_text assert etree.QName(element) == etree.QName(other_element), \ '{} != {}'.format(etree.QName(element), etree.QName(other_element)) assert element.attrib == other_element.attrib assert compare_text(element.text, other_element.text), \ '{} != {}'.format(element.text, other_element.text) assert compare_text(element.tail, other_element.tail), \ '{} != {}'.format(element.tail, other_element.tail) assert len(element) == len(other_element), \ '{}: {} / {}'.format(element.tag, len(element), len(other_element)) assert all(equal_subtree(x, y, ignore_whitespaces) for x, y in zip(element, other_element)) return True
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)
def get_payments(self, element): tag = etree.QName(element) details = element.find('./{%s}NtryDtls' % tag.namespace) if details is None: # Version 1 doesn't have NtryDtls but directly TxDtls details = element.find('./{%s}TxDtls' % tag.namespace) if details is None: return instr_id = details.find('.//{%s}InstrId' % tag.namespace) if instr_id is not None: payments = self.Payment.search([ ('sepa_instruction_id', '=', instr_id.text), ('kind', '=', self.get_payment_kind(element)), ]) return payments end_to_end_id = details.find('.//{%s}EndToEndId' % tag.namespace) if end_to_end_id is not None: payments = self.Payment.search([ ('sepa_end_to_end_id', '=', end_to_end_id.text), ('kind', '=', self.get_payment_kind(element)), ]) return payments
def FromXml(cls, element): elementTag = etree.QName(element.tag) if (elementTag.localname != "ipxactFile"): raise PyIpxactException("Expected tag 'ipxactFile'.") for element2 in element: element3 = etree.QName(element2) if (element3.localname == "vlnv"): vendor = element2.get("vendor") library = element2.get("library") name2 = element2.get("name") version = element2.get("version") vlnv = Vlnv(vendor, library, name2, version) elif (element3.localname == "name"): name = element2.text elif (element3.localname == "description"): description = element2.text else: raise PyIpxactException("Unsupported tag '{0}' in node 'ipxactFile'.".format(element.localname)) ipxactFile = cls(vlnv, name, description) return ipxactFile
def generateInitMethod(factory, classinfos): """ Methods that generates the different methods for setting and getting the attributes """ def initMethod(self): if "base" in classinfos: classinfos["base"]._init_(self) for attribute in classinfos["attributes"]: attribute["attr_type"] = FindTypeInfos(factory, attribute["attr_type"]) if attribute["use"] == "required": self.set(attribute["name"], attribute["attr_type"]["generate"](attribute["attr_type"]["initial"]())) for element in classinfos["elements"]: if element["type"] != CHOICE: element_name = ( etree.QName(factory.NSMAP["xhtml"], "p") if element["type"] == ANY else factory.etreeNamespaceFormat % element["name"]) initial = GetElementInitialValue(factory, element) if initial is not None: map(self.append, initial) return initMethod
def parse_meta(meta, hname): syslog_servers = [] dhcp_servers = [] ntp_servers = [] mgmt_routes = [] deployment_id = None device_metas = meta.find(str(QName(ns, "Devices"))) for device in device_metas.findall(str(QName(ns1, "DeviceMetadata"))): if device.find(str(QName(ns1, "Name"))).text == hname: properties = device.find(str(QName(ns1, "Properties"))) for device_property in properties.findall(str(QName(ns1, "DeviceProperty"))): name = device_property.find(str(QName(ns1, "Name"))).text value = device_property.find(str(QName(ns1, "Value"))).text value_group = value.split(';') if value and value != "" else [] if name == "DhcpResources": dhcp_servers = value_group elif name == "NtpResources": ntp_servers = value_group elif name == "SyslogResources": syslog_servers = value_group elif name == "ForcedMgmtRoutes": mgmt_routes = value_group elif name == "DeploymentId": deployment_id = value return syslog_servers, dhcp_servers, ntp_servers, mgmt_routes, deployment_id
def test_serialize_simple(): custom_type = xsd.Element( etree.QName('http://tests.python-zeep.org/', 'authentication'), xsd.ComplexType( xsd.Sequence([ xsd.Element( etree.QName('http://tests.python-zeep.org/', 'name'), xsd.String()), xsd.Attribute( etree.QName('http://tests.python-zeep.org/', 'attr'), xsd.String()), ]) )) obj = custom_type(name='foo', attr='x') assert obj.name == 'foo' assert obj.attr == 'x' result = serialize_object(obj) assert result == { 'name': 'foo', 'attr': 'x', }
def test_choice_mixed(): xsd_type = xsd.ComplexType( xsd.Sequence([ xsd.Choice([ xsd.Element('item_1', xsd.String()), xsd.Element('item_2', xsd.String()), ]), xsd.Element('item_2', xsd.String()) ]), qname=QName('http://tests.python-zeep.org', 'container') ) expected = '{http://tests.python-zeep.org}container(({item_1: xsd:string} | {item_2: xsd:string}), item_2__1: xsd:string)' assert xsd_type.signature() == expected args = tuple([]) kwargs = {'item_1': 'value-1', 'item_2__1': 'value-2'} result = valueobjects._process_signature(xsd_type, args, kwargs) assert result == { 'item_1': 'value-1', 'item_2': None, 'item_2__1': 'value-2', }
def test_signature_complex_type_choice_sequence(): 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.Sequence([ xsd.Element( etree.QName('http://tests.python-zeep.org/', 'item_2_1'), xsd.String()), xsd.Element( etree.QName('http://tests.python-zeep.org/', 'item_2_2'), xsd.String()), ]) ]) )) assert custom_type.signature() == ( '{http://tests.python-zeep.org/}authentication(({item_1: xsd:string} | {item_2_1: xsd:string, item_2_2: xsd:string}))')
def test_signature_complex_type_sequence_with_any(): 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() ]) ) ) ]) )) assert custom_type.signature() == ( '{http://tests.python-zeep.org/}authentication(({item_1: xsd:string} | {item_2: {_value_1: ANY}}))')
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}})' + ')')
def test_build_group_occurs_1_invalid_kwarg(): custom_type = xsd.Element( etree.QName('http://tests.python-zeep.org/', 'authentication'), xsd.ComplexType( xsd.Group( etree.QName('http://tests.python-zeep.org/', 'foobar'), 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()), ]), min_occurs=1, max_occurs=1) )) with pytest.raises(TypeError): custom_type(item_1='foo', item_2='bar', error=True)
def test_build_group_min_occurs_2_invalid_kwarg(): custom_type = xsd.Element( etree.QName('http://tests.python-zeep.org/', 'authentication'), xsd.ComplexType( xsd.Group( etree.QName('http://tests.python-zeep.org/', 'foobar'), 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()), ]), min_occurs=2, max_occurs=2) )) with pytest.raises(TypeError): custom_type(_value_1=[ {'item_1': 'foo', 'item_2': 'bar', 'error': True}, {'item_1': 'foo', 'item_2': 'bar'}, ])
def test_container_elements(): custom_type = xsd.Element( etree.QName('http://tests.python-zeep.org/', 'authentication'), xsd.ComplexType( xsd.Sequence([ xsd.Element( etree.QName('http://tests.python-zeep.org/', 'username'), xsd.String()), xsd.Element( etree.QName('http://tests.python-zeep.org/', 'password'), xsd.String()), xsd.Any(), ]) )) # sequences custom_type(username='foo', password='bar')
def test_invalid_kwarg(): custom_type = xsd.Element( etree.QName('http://tests.python-zeep.org/', 'authentication'), xsd.ComplexType( xsd.Sequence([ xsd.Element( etree.QName('http://tests.python-zeep.org/', 'username'), xsd.String()), xsd.Element( etree.QName('http://tests.python-zeep.org/', 'password'), xsd.String()), ]) )) with pytest.raises(TypeError): custom_type(something='is-wrong')
def test_attr_name(): custom_type = xsd.Element( etree.QName('http://tests.python-zeep.org/', 'authentication'), xsd.ComplexType( xsd.Sequence([ xsd.Element( etree.QName('http://tests.python-zeep.org/', 'UserName'), xsd.String(), attr_name='username'), xsd.Element( etree.QName('http://tests.python-zeep.org/', 'Password_x'), xsd.String(), attr_name='password'), ]) )) # sequences custom_type(username='foo', password='bar')
def test_sequence_parse_anytype(): custom_type = xsd.Element( etree.QName('http://tests.python-zeep.org/', 'container'), xsd.ComplexType( xsd.Sequence([ xsd.Element( etree.QName('http://tests.python-zeep.org/', 'item_1'), xsd.AnyType()), ]) )) expected = etree.fromstring(""" <ns0:container xmlns:ns0="http://tests.python-zeep.org/"> <ns0:item_1>foo</ns0:item_1> </ns0:container> """) obj = custom_type.parse(expected, None) assert obj.item_1 == 'foo'
def __init__(self, name, type_=None, min_occurs=1, max_occurs=1, nillable=False, default=None, is_global=False, attr_name=None): if name is None: raise ValueError("name cannot be None", self.__class__) if not isinstance(name, etree.QName): name = etree.QName(name) self.name = name.localname if name else None self.qname = name self.type = type_ self.min_occurs = min_occurs self.max_occurs = max_occurs self.nillable = nillable self.is_global = is_global self.default = default self.attr_name = attr_name or self.name # assert type_
def visit_restriction_simple_content(self, node, parent): """ Definition:: <restriction base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType?, ( minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits |fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern)* )?, ((attribute | attributeGroup)*, anyAttribute?)) </restriction> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, 'base') base_type = self._get_type(base_name) return base_type, []
def visit_extension_simple_content(self, node, parent): """ Definition:: <extension base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, ((attribute | attributeGroup)*, anyAttribute?)) </extension> """ base_name = qname_attr(node, 'base') base_type = self._get_type(base_name) annotation, children = self._pop_annotation(node.getchildren()) attributes = self._process_attributes(node, children) return base_type, attributes
def _create_qname(self, name): if not isinstance(name, etree.QName): name = etree.QName(name) # Handle reserved namespace if name.namespace == 'xml': name = etree.QName( 'http://www.w3.org/XML/1998/namespace', name.localname) # Various xsd builders assume that some schema's are available by # default (actually this is mostly just the soap-enc ns). So live with # that fact and handle it by auto-importing the schema if it is # referenced. if ( name.namespace in AUTO_IMPORT_NAMESPACES and not self.document.is_imported(name.namespace) ): logger.debug( "Auto importing missing known schema: %s", name.namespace) import_node = etree.Element( tags.import_, namespace=name.namespace, schemaLocation=name.namespace) self.visit_import(import_node, None) return name
def _create_qname(self, name): """Create an `lxml.etree.QName()` object for the given qname string. This also expands the shorthand notation. :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)
def _resolve_header(self, info, definitions, parts): name = etree.QName(self.nsmap['soap-env'], 'Header') container = xsd.All(consume_other=True) if not info: return xsd.Element(name, xsd.ComplexType(container)) for item in info: message_name = item['message'].text part_name = item['part'] message = definitions.get('messages', message_name) if message == self.abstract: del parts[part_name] part = message.parts[part_name] if part.element: element = part.element.clone() element.attr_name = part_name else: element = xsd.Element(part_name, part.type) container.append(element) return xsd.Element(name, xsd.ComplexType(container))
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)
def parse_device(device): lo_prefix = None mgmt_prefix = None d_type = None # don't shadow type() hwsku = None name = None if str(QName(ns3, "type")) in device.attrib: d_type = device.attrib[str(QName(ns3, "type"))] for node in device: if node.tag == str(QName(ns, "Address")): lo_prefix = node.find(str(QName(ns2, "IPPrefix"))).text elif node.tag == str(QName(ns, "ManagementAddress")): mgmt_prefix = node.find(str(QName(ns2, "IPPrefix"))).text elif node.tag == str(QName(ns, "Hostname")): name = node.text elif node.tag == str(QName(ns, "HwSku")): hwsku = node.text return (lo_prefix, mgmt_prefix, name, hwsku, d_type)
def tag_to_object(tag, check_ns=False): q = QName(tag) if check_ns and q.namespace != openmath_ns: raise ValueError('Invalid namespace') return omtags[q.localname]
def _elements_to_dict(self, results): """ Take simple elements and turn to dictionary """ for element in results: tag = etree.QName(element.tag) if tag.localname in self._dict: # handle arrays! if not isinstance(self._dict[tag.localname], list): values = [self._dict[tag.localname]] # Grab the original self._dict[tag.localname] = values self._dict[tag.localname].append(element.text) else: self._dict[tag.localname] = element.text
def _svg(self, tag=None, version='1.1', **kwargs): if tag is None: tag = ET.QName(self._SVG_namespace, "svg") dimension = self.units(self.pixel_size) return ET.Element( tag, width=dimension, height=dimension, version=version, **kwargs)
def _rect(self, row, col, tag=None): if tag is None: tag = ET.QName(self._SVG_namespace, "rect") x, y = self.pixel_box(row, col)[0] return ET.Element( tag, x=self.units(x), y=self.units(y), width=self.unit_size, height=self.unit_size)
def make_path(self): subpaths = self._generate_subpaths() return ET.Element( ET.QName("path"), style=self.QR_PATH_STYLE, d=' '.join(subpaths), id="qr-path" )
def addAgent(softwareName): # 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": # URI to isoBuster Wikidata page agentIdentifierValue.text = "https://www.wikidata.org/wiki/Q304733" agentName.text = "isoBuster" elif softwareName == "dbpoweramp": # URI to dBpoweramp Wikidata page agentIdentifierValue.text = "https://www.wikidata.org/wiki/Q1152133" agentName.text = "dBpoweramp" return(agent)
def _add_header(self, envelope): header = ElementTree.SubElement(envelope, '{%s}Header' % NS_SOAP_ENV) qn_must_understand = ElementTree.QName(NS_SOAP_ENV, 'mustUnderstand') to_elem = ElementTree.SubElement(header, '{%s}To' % NS_WS_ADDR) to_elem.set(qn_must_understand, 'true') to_elem.text = self.endpoint resource_elem = ElementTree.SubElement(header, '{%s}ResourceURI' % NS_WSMAN) resource_elem.set(qn_must_understand, 'true') resource_elem.text = self.resource_uri msg_id_elem = ElementTree.SubElement(header, '{%s}MessageID' % NS_WS_ADDR) msg_id_elem.set(qn_must_understand, 'true') msg_id_elem.text = 'uuid:%s' % uuid.uuid4() reply_to_elem = ElementTree.SubElement(header, '{%s}ReplyTo' % NS_WS_ADDR) reply_to_addr_elem = ElementTree.SubElement(reply_to_elem, '{%s}Address' % NS_WS_ADDR) reply_to_addr_elem.text = NS_WS_ADDR_ANONYM_ROLE return header
def build_xml(dataset): author = dataset['author'] publisher = config['ckanext.ands.publisher'] # Dev prefix default doi_prefix = config.get('ckanext.ands.doi_prefix', '10.5072/') # TODO what should this be? ands_client_id = config['ckanext.ands.client_id'] namespaces = { 'xsi': "http://www.w3.org/2001/XMLSchema-instance", None: "http://datacite.org/schema/kernel-3", } Root = ElementMaker( nsmap=namespaces ) E = ElementMaker() xml = Root.resource( E.identifier(doi_prefix + ands_client_id, identifierType="DOI"), E.creators(E.creator(E.creatorName(author))), E.titles(E.title(dataset['title'])), E.publisher(publisher), E.publicationYear("{}".format(package_get_year(dataset))), E.language('en'), E.resourceType('gDMCP Dataset', resourceTypeGeneral="Dataset"), E.descriptions(E.description(dataset['notes'], descriptionType="Abstract")), ) xml.attrib[etree.QName(namespaces['xsi'], 'schemaLocation')] = "http://datacite.org/schema/kernel-3 http://schema.datacite.org/meta/kernel-3/metadata.xsd" return etree.tostring(xml, pretty_print=True)
def qname (tag): try: return etree.QName(tag) except ValueError: prefix, base = tag.split(":") return etree.QName(NSMAP[prefix], base)
def filter_tag_match (filter_tag, elm_tag): fqname = etree.QName(filter_tag) eqname = qname(elm_tag) if not fqname.namespace: return fqname.localname == eqname.localname return fqname == eqname
def match(self, e): name = QName(e.tag).localname.lower() return name == 'title'
def match(self, e): name = QName(e.tag).localname.lower() return name in ('link', 'guid')
def match(self, e): name = QName(e.tag).localname.lower() return name in ('pubdate', 'updated')
def match(self, e): name = QName(e.tag).localname.lower() return name == 'category'
def match(self, e): name = QName(e.tag).localname.lower() return name in ('encoded', 'description', 'content', 'summary')
def extract_namespace(tag): qname = etree.QName(tag) return qname.namespace, qname.localname
def __init__(self, address, port, filename=None): """Loads and parses an xml-file from a FritzBox.""" if address is None: source = filename else: source = 'http://{0}:{1}/{2}'.format(address, port, filename) tree = etree.parse(source) self.root = tree.getroot() self.namespace = etree.QName(self.root.tag).namespace
def nodename(self, name): """Extends name with the xmlns-prefix to a valid nodename.""" return etree.QName(self.root, name)
def get_localname(element): """ Gets the element's local tag name. """ return etree.QName(element).localname
def merge(src='previous_result', dst='root'): """ A wrapper around :func:`inxs.lxml_util.merge_nodes` that passes the objects referenced by ``src`` and ``dst``. """ def handler(transformation): _src = transformation._available_symbols[src] _dst = transformation._available_symbols[dst] assert etree.QName(_src).text == etree.QName(_dst).text, \ f'{etree.QName(_src).text} != {etree.QName(_dst).text}' lxml_utils.merge_nodes(_src, _dst) return handler
def set_localname(name): """ Sets the element's localname to ``name``. """ def handler(element, previous_result): namespace = etree.QName(element).namespace if namespace is None: qname = etree.QName(name) else: qname = etree.QName(namespace, name) element.tag = qname.text return previous_result return handler
def strip_namespace(element, previous_result): """ Removes the namespace from the element. When used, :func:`cleanup_namespaces` should be applied at the end of the transformation. """ element.tag = etree.QName(element).localname return previous_result