Python xml.etree.ElementTree 模块,QName() 实例源码
我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用xml.etree.ElementTree.QName()。
def fixtag(tag, namespaces):
# given a decorated tag (of the form {uri}tag), return prefixed
# tag and namespace declaration, if any
if isinstance(tag, ET.QName):
tag = tag.text
namespace_uri, tag = tag[1:].split("}", 1)
prefix = namespaces.get(namespace_uri)
if prefix is None:
prefix = "ns%d" % len(namespaces)
namespaces[namespace_uri] = prefix
if prefix == "xml":
xmlns = None
else:
xmlns = ("xmlns:%s" % prefix, namespace_uri)
else:
xmlns = None
return "%s:%s" % (prefix, tag), xmlns
def probe_metric(service_url, metric):
'''
Query the service at the given URL for the given metric value.
Assumptions are made about the name of the method and output parameters
which are only valid for the WanCommonInterfaceConfig service.
'''
envelope = E(QName(ns['s'], 'Envelope'), {QName(ns['s'], 'encodingStyle'): 'http://schemas.xmlsoap.org/soap/encoding/'})
body = sE(envelope, QName(ns['s'], 'Body'))
method = sE(body, QName(ns['i'], 'Get{}'.format(metric)))
request_tree = ET(envelope)
with io.BytesIO() as out:
out.write(b'<?xml version="1.0"?>')
request_tree.write(out, encoding='utf-8')
out.write(b'\r\n') # or else my Belkin F5D8236-4 never responds...
req = urllib.request.Request(service_url, out.getvalue())
req.add_header('Content-Type', 'text/xml')
req.add_header('SOAPAction', '"{}#{}"'.format(ns['i'], 'Get{}'.format(metric)))
with urllib.request.urlopen(req) as result:
result_tree = ElementTree.parse(result)
return int(result_tree.findtext('.//New{}'.format(metric), namespaces=ns))
def _generate_chat(self, to, from_, body):
data = _FormData()
data.add_text('from', from_, 'plain')
data.add_text('to', to, 'plain')
data.add_text('body', body, 'plain')
message_element = ElementTree.Element(
ElementTree.QName('jabber:client', 'message'),
{'from': from_, 'to': to, 'type': 'chat'})
body_element = ElementTree.SubElement(
message_element,
ElementTree.QName('jabber:client', 'body'))
body_element.text = body
data.add_text('stanza',
ElementTree.tostring(message_element, encoding='utf-8'),
'xml')
return data
def _generate_presence_available(self, to, from_, show=None):
data = _FormData()
data.add_text('from', from_, 'plain')
data.add_text('to', to, 'plain')
# If the "presence" attribute is absent, "available" is assumed and it is
# not sent by Google Talk.
presence_element = ElementTree.Element(
ElementTree.QName('jabber:client', 'presence'),
{'from': from_, 'to': to})
if show: # This is currently a dead code path.
# The show element is optional according to RFC 3921, 2.2.2.1.
data.add_text('show', show, 'plain')
show_element = ElementTree.SubElement(
presence_element,
ElementTree.QName('jabber:client', 'show'))
show_element.text = show
data.add_text('stanza',
ElementTree.tostring(presence_element, 'utf-8'),
'xml')
return data
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 _generate_presence_type(self, to, from_, presence_type):
data = _FormData()
data.add_text('from', from_, 'plain')
data.add_text('to', to, 'plain')
presence_element = ElementTree.Element(
ElementTree.QName('jabber:client', 'presence'),
{'from': from_, 'to': to, 'type': presence_type})
data.add_text('stanza',
ElementTree.tostring(presence_element, 'utf-8'),
'xml')
return data
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 _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 nodename(self, name):
#self.debug("name: %s, QName: %s" %(name, ET.QName(self.root, name).text))
"""Extends name with the xmlns-prefix to a valid nodename."""
found = re.match('{.*({.*}).*}(.*$)', ET.QName(self.root, name).text)
if found:
# self.debug("result: " + found.group(1) + found.group(2))
return found.group(1) + found.group(2)
else:
return ""
def _from_xml_node(self, node, listnames):
attrNil = node.get(str(etree.QName(constants.XSI_NAMESPACE, "nil")))
attrType = node.get(str(etree.QName(
self.metadata.get('xmlns'), "type")))
if (attrNil and attrNil.lower() == 'true'):
return None
elif not len(node) and not node.text:
if (attrType and attrType == constants.TYPE_DICT):
return {}
elif (attrType and attrType == constants.TYPE_LIST):
return []
else:
return ''
elif (len(node) == 0 and node.text):
converters = {constants.TYPE_BOOL:
lambda x: x.lower() == 'true',
constants.TYPE_INT:
lambda x: int(x),
constants.TYPE_LONG:
lambda x: long(x),
constants.TYPE_FLOAT:
lambda x: float(x)}
if attrType and attrType in converters:
return converters[attrType](node.text)
else:
return node.text
elif self._get_key(node.tag) in listnames:
return [self._from_xml_node(n, listnames) for n in node]
else:
result = dict()
for attr in node.keys():
if (attr == 'xmlns' or
attr.startswith('xmlns:') or
attr == constants.XSI_ATTR or
attr == constants.TYPE_ATTR):
continue
result[self._get_key(attr)] = node.get(attr)
children = list(node)
for child in children:
result[self._get_key(child.tag)] = self._from_xml_node(
child, listnames)
return result
def _from_xml_node(self, node, listnames):
"""Convert a minidom node to a simple Python type.
:param node: minidom node name
:param listnames: list of XML node names whose subnodes should
be considered list items.
"""
attrNil = node.get(str(etree.QName(constants.XSI_NAMESPACE, "nil")))
attrType = node.get(str(etree.QName(
self.metadata.get('xmlns'), "type")))
if (attrNil and attrNil.lower() == 'true'):
return None
elif not len(node) and not node.text:
if (attrType and attrType == constants.TYPE_DICT):
return {}
elif (attrType and attrType == constants.TYPE_LIST):
return []
else:
return ''
elif (len(node) == 0 and node.text):
converters = {constants.TYPE_BOOL:
lambda x: x.lower() == 'true',
constants.TYPE_INT:
lambda x: int(x),
constants.TYPE_LONG:
lambda x: long(x),
constants.TYPE_FLOAT:
lambda x: float(x)}
if attrType and attrType in converters:
return converters[attrType](node.text)
else:
return node.text
elif self._get_key(node.tag) in listnames:
return [self._from_xml_node(n, listnames) for n in node]
else:
result = dict()
for attr in node.keys():
if (attr == 'xmlns' or
attr.startswith('xmlns:') or
attr == constants.XSI_ATTR or
attr == constants.TYPE_ATTR):
continue
result[self._get_key(attr)] = node.get(attr)
children = list(node)
for child in children:
result[self._get_key(child.tag)] = self._from_xml_node(
child, listnames)
return result
def _from_xml_node(self, node, listnames):
"""Convert a minidom node to a simple Python type.
:param node: minidom node name
:param listnames: list of XML node names whose subnodes should
be considered list items.
"""
attrNil = node.get(str(etree.QName(constants.XSI_NAMESPACE, "nil")))
attrType = node.get(str(etree.QName(
self.metadata.get('xmlns'), "type")))
if (attrNil and attrNil.lower() == 'true'):
return None
elif not len(node) and not node.text:
if (attrType and attrType == constants.TYPE_DICT):
return {}
elif (attrType and attrType == constants.TYPE_LIST):
return []
else:
return ''
elif (len(node) == 0 and node.text):
converters = {constants.TYPE_BOOL:
lambda x: x.lower() == 'true',
constants.TYPE_INT:
lambda x: int(x),
constants.TYPE_LONG:
lambda x: long(x),
constants.TYPE_FLOAT:
lambda x: float(x)}
if attrType and attrType in converters:
return converters[attrType](node.text)
else:
return node.text
elif self._get_key(node.tag) in listnames:
return [self._from_xml_node(n, listnames) for n in node]
else:
result = dict()
for attr in node.keys():
if (attr == 'xmlns' or
attr.startswith('xmlns:') or
attr == constants.XSI_ATTR or
attr == constants.TYPE_ATTR):
continue
result[self._get_key(attr)] = node.get(attr)
children = list(node)
for child in children:
result[self._get_key(child.tag)] = self._from_xml_node(
child, listnames)
return result