Convert XML elementtree to dictionary.

        Converts the actual response from the ILO for an API
        to the dictionary.
978349
def _elementtree_to_dict(self, element):
        
        node = {}
        text = getattr(element, 'text')
        if text is not None:
            text = text.strip()
            if len(text) != 0:
                node['text'] = text
        node.update(element.items())  # element's attributes
        child_nodes = {}
        for child in element:  # element's children
            child_nodes.setdefault(child.tag, []).append(
                self._elementtree_to_dict(child))
        # convert all single-element lists into non-lists
        for key, value in child_nodes.items():
            if len(value) == 1:
                child_nodes[key] = value[0]
        node.update(child_nodes.items())
        return node
473361
def _node_to_dict(cls, node, json, json_fields):
        
        if json:
            pk_name = node.get_pk_name()
            # jqTree or jsTree format
            result = {'id': getattr(node, pk_name), 'label': node.__repr__()}
            if json_fields:
                result.update(json_fields(node))
        else:
            result = {'node': node}
        return result
1238194
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'log_messages') and self.log_messages is not None:
            _dict['log_messages'] = [x._to_dict() for x in self.log_messages]
        if hasattr(self, 'text') and self.text is not None:
            _dict['text'] = self.text
        if hasattr(self, 'generic') and self.generic is not None:
            _dict['generic'] = [x._to_dict() for x in self.generic]
        if hasattr(self, 'nodes_visited') and self.nodes_visited is not None:
            _dict['nodes_visited'] = self.nodes_visited
        if hasattr(self, 'nodes_visited_details'
                  ) and self.nodes_visited_details is not None:
            _dict['nodes_visited_details'] = [
                x._to_dict() for x in self.nodes_visited_details
            ]
        if hasattr(self, '_additionalProperties'):
            for _key in self._additionalProperties:
                _value = getattr(self, _key, None)
                if _value is not None:
                    _dict[_key] = _value
        return _dict
633277
def xmlresponse(py_data):
    
    xroot = ElementTree.Element('methodResponse')
    xparams = ElementTree.SubElement(xroot, 'params')
    xparam = ElementTree.SubElement(xparams, 'param')

    type_map = {'bool': 'boolean',
                'float': 'double',
                'str': 'string',
                'unicode': 'string',
                'datetime': 'dateTime.iso8601',
                'date': 'date.iso8601',
                'time': 'time.iso8601'}

    def xobj(xparent, py_obj):
        # convert a list of information
        if type(py_obj) in (tuple, list):
            xarr = ElementTree.SubElement(xparent, 'array')
            xdata = ElementTree.SubElement(xarr, 'data')
            for val in py_obj:
                xval = ElementTree.SubElement(xdata, 'value')
                xobj(xval, val)

        # convert a dictionary of information
        elif type(py_obj) == dict:
            xstruct = ElementTree.SubElement(xparent, 'struct')
            for key, val in py_obj.items():
                xmember = ElementTree.SubElement(xstruct, 'member')
                xname = ElementTree.SubElement(xmember, 'name')
                xname.text = key
                xval = ElementTree.SubElement(xmember, 'value')
                xobj(xval, val)

        # convert a None value
        elif py_obj is None:
            ElementTree.SubElement(xparent, 'nil')

        # convert a basic value
        else:
            typ = type(py_obj).__name__
            typ = type_map.get(typ, typ)
            xitem = ElementTree.SubElement(xparent, typ)

            # convert a datetime/date/time
            if isinstance(py_obj, datetime.date) or \
                    isinstance(py_obj, datetime.time) or \
                    isinstance(py_obj, datetime.datetime):

                if py_obj.tzinfo and pytz:
                    data = py_obj.astimezone(pytz.utc).replace(tzinfo=None)
                    xitem.text = data.isoformat()
                else:
                    xitem.text = py_obj.isoformat()

            # convert a boolean
            elif type(py_obj) == bool:
                xitem.text = nstr(int(py_obj))

            # convert a non-string object
            elif not type(py_obj) in (str, unicode):
                xitem.text = nstr(py_obj)

            # convert a string object
            else:
                xitem.text = py_obj

    xobj(xparam, py_data)
    projex.text.xmlindent(xroot)
    return ElementTree.tostring(xroot)
538330
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'xpaths') and self.xpaths is not None:
            _dict['xpaths'] = self.xpaths
        return _dict
847318
def as_dict(self):
        

        element_dict = super(HTMLElement, self).as_dict()

        if hasattr(self, 'content'):
            element_dict['content'] = self.content

        return element_dict
794456
def resource_as_xml(self, resource):
        
        e = self.resource_etree_element(resource)
        if (sys.version_info >= (3, 0)):
            # python3.x
            return(tostring(e, encoding='unicode', method='xml'))
        elif (sys.version_info >= (2, 7)):
            s = tostring(e, encoding='UTF-8', method='xml')
        else:
            # must not specify method='xml' in python2.6
            s = tostring(e, encoding='UTF-8')
        # Chop off XML declaration that is added in 2.x... sigh
        return(s.replace("<?xml version='1.0' encoding='UTF-8'?>\n", ''))
448169
def _to_dict(xmltree):
    '''
    
    '''
    # If this object has no children, the for..loop below will return nothing
    # for it, so just return a single dict representing it.
    if not xmltree.getchildren():
        name = _conv_name(xmltree.tag)
        return {name: xmltree.text}

    xmldict = {}
    for item in xmltree:
        name = _conv_name(item.tag)

        if name not in xmldict:
            if item.getchildren():
                xmldict[name] = _to_dict(item)
            else:
                xmldict[name] = item.text
        else:
            # If a tag appears more than once in the same place, convert it to
            # a list. This may require that the caller watch for such a thing
            # to happen, and behave accordingly.
            if not isinstance(xmldict[name], list):
                xmldict[name] = [xmldict[name]]
            xmldict[name].append(_to_dict(item))
    return xmldict
1355228
def xml2dict(root):
    
    output = {}
    if root.items():
        output.update(dict(root.items()))

    for element in root:
        if element:
            if len(element) == 1 or element[0].tag != element[1].tag:
                one_dict = xml2dict(element)
            else:
                one_dict = {ns(element[0].tag): xml2list(element)}

            if element.items():
                one_dict.update(dict(element.items()))
            output.update({ns(element.tag): one_dict})

        elif element.items():
            output.update({ns(element.tag): dict(element.items())})

        else:
            output.update({ns(element.tag): element.text})

    return output
635034
def to_dict(self, **kw):
        
        """
        _, value = helpers.etree_to_dict(self._xml, **kw).popitem()
        return value
580026
def to_xml(self, xmllint=False):
        
        root = self._tree.getroot()
        ret = ET.tostring(ET.ElementTree(root), pretty_print=True)
        if xmllint:
            ret = xmllint_format(ret)
        return ret
604908
def toString(self):
        
        xprofile = self.toXml()
        projex.text.xmlindent(xprofile)
        return ElementTree.tostring(xprofile)
296624
def _elements_to_dict(data, position, obj_end, opts):
    """"""
    result = opts.document_class()
    pos = position
    for key, value, pos in _iterate_elements(data, position, obj_end, opts):
        result[key] = value
    if pos != obj_end:
        raise InvalidBSON('bad object or element length')
    return result
915657
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'element_pair') and self.element_pair is not None:
            _dict['element_pair'] = [x._to_dict() for x in self.element_pair]
        if hasattr(self, 'identical_text') and self.identical_text is not None:
            _dict['identical_text'] = self.identical_text
        if hasattr(self, 'provenance_ids') and self.provenance_ids is not None:
            _dict['provenance_ids'] = self.provenance_ids
        if hasattr(self, 'significant_elements'
                  ) and self.significant_elements is not None:
            _dict['significant_elements'] = self.significant_elements
        return _dict
815980
def to_element(self, root_name=None):
        """"""
        if not root_name:
            root_name = self.nodename
        elem = ElementTreeBuilder.Element(root_name)
        for attrname in self.serializable_attributes():
            # Only use values that have been loaded into the internal
            # __dict__. For retrieved objects we look into the XML response at
            # access time, so the internal __dict__ contains only the elements
            # that have been set on the client side.
            try:
                value = self.__dict__[attrname]
            except KeyError:
                continue

            if attrname in self.xml_attribute_attributes:
                elem.attrib[attrname] = six.text_type(value)
            else:
                sub_elem = self.element_for_value(attrname, value)
                elem.append(sub_elem)

        return elem
69754
def deserialize(self, xml_input, *args, **kwargs):
        
        return xmltodict.parse(xml_input, *args, **kwargs)
399121
def as_dict(self):
        

        element_dict = dict()
        if hasattr(self, 'namespace'):
            element_dict['namespace'] = self.namespace
        if hasattr(self, 'name'):
            element_dict['name'] = self.name
        if hasattr(self, 'text'):
            element_dict['text'] = self.text

        attr_dict = dict()
        for attr in self.attrs:
            if hasattr(self, attr):
                attr_dict[attr] = getattr(self, attr)
        element_dict['attrs'] = attr_dict

        return element_dict