Python xml.etree.ElementTree.QName() Examples

The following are 29 code examples of xml.etree.ElementTree.QName(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xml.etree.ElementTree , or try the search function .
Example #1
Source File: xmpp_request_handler.py    From browserscope with Apache License 2.0 6 votes vote down vote up
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 
Example #2
Source File: mbxml.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: xmpp_request_handler.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
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 
Example #4
Source File: xmpp_request_handler.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: xmpp_request_handler.py    From browserscope with Apache License 2.0 6 votes vote down vote up
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 
Example #6
Source File: Objects.py    From IFIscripts with MIT License 5 votes vote down vote up
def _qsplit(tagname):
    """Requires string input.  Returns namespace and local tag name as a pair.  I could've sworn this was a basic implementation gimme, but ET.QName ain't it."""
    _typecheck(tagname, str)
    if tagname[0] == "{":
        i = tagname.rfind("}")
        return ( tagname[1:i], tagname[i+1:] )
    else:
        return (None, tagname) 
Example #7
Source File: svg.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
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"
        ) 
Example #8
Source File: svg.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #9
Source File: svg.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #10
Source File: svg.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
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"
        ) 
Example #11
Source File: svg.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #12
Source File: svg.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #13
Source File: local.py    From gradleplease-workflow with Apache License 2.0 5 votes vote down vote up
def findtext(element, tag, alt='', ns='http://maven.apache.org/POM/4.0.0'):
    fulltag = str(ET.QName(ns, tag))
    return element.findtext(fulltag, alt) 
Example #14
Source File: xmpp_request_handler.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
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 
Example #15
Source File: serializer.py    From eclcli with Apache License 2.0 5 votes vote down vote up
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_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 
Example #16
Source File: svg.py    From teleport with Apache License 2.0 5 votes vote down vote up
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"
        ) 
Example #17
Source File: svg.py    From teleport with Apache License 2.0 5 votes vote down vote up
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) 
Example #18
Source File: svg.py    From teleport with Apache License 2.0 5 votes vote down vote up
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) 
Example #19
Source File: svg.py    From teleport with Apache License 2.0 5 votes vote down vote up
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) 
Example #20
Source File: svg.py    From teleport with Apache License 2.0 5 votes vote down vote up
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) 
Example #21
Source File: svg.py    From teleport with Apache License 2.0 5 votes vote down vote up
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"
        ) 
Example #22
Source File: svg.py    From teleport with Apache License 2.0 5 votes vote down vote up
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) 
Example #23
Source File: svg.py    From teleport with Apache License 2.0 5 votes vote down vote up
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) 
Example #24
Source File: xmpp_request_handler.py    From browserscope with Apache License 2.0 5 votes vote down vote up
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 
Example #25
Source File: serializer.py    From eclcli with Apache License 2.0 4 votes vote down vote up
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_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 
Example #26
Source File: serializer.py    From eclcli with Apache License 2.0 4 votes vote down vote up
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_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 
Example #27
Source File: serializers.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
def _serialize_html(write, elem, format):
    tag = elem.tag
    text = elem.text
    if tag is Comment:
        write("<!--%s-->" % _escape_cdata(text))
    elif tag is ProcessingInstruction:
        write("<?%s?>" % _escape_cdata(text))
    elif tag is None:
        if text:
            write(_escape_cdata(text))
        for e in elem:
            _serialize_html(write, e, format)
    else:
        namespace_uri = None
        if isinstance(tag, QName):
            # QNAME objects store their data as a string: `{uri}tag`
            if tag.text[:1] == "{":
                namespace_uri, tag = tag.text[1:].split("}", 1)
            else:
                raise ValueError('QName objects must define a tag.')
        write("<" + tag)
        items = elem.items()
        if items:
            items = sorted(items)  # lexical order
            for k, v in items:
                if isinstance(k, QName):
                    # Assume a text only QName
                    k = k.text
                if isinstance(v, QName):
                    # Assume a text only QName
                    v = v.text
                else:
                    v = _escape_attrib_html(v)
                if k == v and format == 'html':
                    # handle boolean attributes
                    write(" %s" % v)
                else:
                    write(' {}="{}"'.format(k, v))
        if namespace_uri:
            write(' xmlns="%s"' % (_escape_attrib(namespace_uri)))
        if format == "xhtml" and tag.lower() in HTML_EMPTY:
            write(" />")
        else:
            write(">")
            if text:
                if tag.lower() in ["script", "style"]:
                    write(text)
                else:
                    write(_escape_cdata(text))
            for e in elem:
                _serialize_html(write, e, format)
            if tag.lower() not in HTML_EMPTY:
                write("</" + tag + ">")
    if elem.tail:
        write(_escape_cdata(elem.tail)) 
Example #28
Source File: merge_xml.py    From se-blender with GNU General Public License v2.0 4 votes vote down vote up
def _serialize_xml(write, elem, qnames, namespaces,
                   short_empty_elements, **kwargs):
    tag = elem.tag
    text = elem.text
    if tag is Comment:
        write("<!--%s-->" % text)
    elif tag is ProcessingInstruction:
        write("<?%s?>" % text)
    else:
        tag = qnames[tag]
        if tag is None:
            if text:
                write(_escape_cdata(text))
            for e in elem:
                _serialize_xml(write, e, qnames, None,
                               short_empty_elements=short_empty_elements)
        else:
            write("<" + tag)
            items = list(elem.items())
            if items or namespaces:
                if namespaces:
                    for v, k in sorted(namespaces.items(),
                                       key=lambda x: x[1]):  # sort on prefix
                        if k:
                            k = ":" + k
                        write(" xmlns%s=\"%s\"" % (
                            k,
                            _escape_attrib(v)
                            ))

                # below is the changed line. assuming attrib is an OrderedDict this will preserve attribute order
                for k, v in elem.attrib.items():
                    if isinstance(k, QName):
                        k = k.text
                    if isinstance(v, QName):
                        v = qnames[v.text]
                    else:
                        v = _escape_attrib(v)
                    write(" %s=\"%s\"" % (qnames[k], v))
            if text or len(elem) or not short_empty_elements:
                write(">")
                if text:
                    write(_escape_cdata(text))
                for e in elem:
                    _serialize_xml(write, e, qnames, None,
                                   short_empty_elements=short_empty_elements)
                write("</" + tag + ">")
            else:
                write(" />")
    if elem.tail:
        write(_escape_cdata(elem.tail)) 
Example #29
Source File: serializer.py    From python-tackerclient with Apache License 2.0 4 votes vote down vote up
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