Turn a list of dicts into XML nodes with tag names taken from the dict
    keys and element text taken from dict values. This is a list of dicts
    so that the XML nodes can be ordered in the XML output.
11616
def struct_to_xml(node, struct):
    
    for obj in struct:
        for k, v in obj.items():
            etree.SubElement(node, k).text = v
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
253591
def etree(self, data, root=None):
        ''''''
        result = self.list() if root is None else root
        if isinstance(data, (self.dict, dict)):
            for key, value in data.items():
                value_is_list = isinstance(value, (self.list, list))
                value_is_dict = isinstance(value, (self.dict, dict))
                # Add attributes and text to result (if root)
                if root is not None:
                    # Handle attribute prefixes (BadgerFish)
                    if self.attr_prefix is not None:
                        if key.startswith(self.attr_prefix):
                            key = key.lstrip(self.attr_prefix)
                            # @xmlns: {$: xxx, svg: yyy} becomes xmlns="xxx" xmlns:svg="yyy"
                            if value_is_dict:
                                raise ValueError('XML namespaces not yet supported')
                            else:
                                result.set(key, self._tostring(value))
                            continue
                    # Handle text content (BadgerFish, GData)
                    if self.text_content is not None:
                        if key == self.text_content:
                            result.text = self._tostring(value)
                            continue
                    # Treat scalars as text content, not children (GData)
                    if self.attr_prefix is None and self.text_content is not None:
                        if not value_is_dict and not value_is_list:
                            result.set(key, self._tostring(value))
                            continue
                # Add other keys as one or more children
                values = value if value_is_list else [value]
                for value in values:
                    elem = self.element(key)
                    if elem is None:
                        continue
                    result.append(elem)
                    # Treat scalars as text content, not children (Parker)
                    if not isinstance(value, (self.dict, dict, self.list, list)):
                        if self.text_content:
                            value = {self.text_content: value}
                    self.etree(value, root=elem)
        else:
            if self.text_content is None and root is not None:
                root.text = self._tostring(data)
            else:
                elem = self.element(self._tostring(data))
                if elem is not None:
                    result.append(elem)
        return result
103771
def data(self, root):
        ''''''
        value = self.dict()
        children = [node for node in root if isinstance(node.tag, basestring)]
        for attr, attrval in root.attrib.items():
            attr = attr if self.attr_prefix is None else self.attr_prefix + attr
            value[attr] = self._fromstring(attrval)
        if root.text and self.text_content is not None:
            text = root.text.strip()
            if text:
                if self.simple_text and len(children) == len(root.attrib) == 0:
                    value = self._fromstring(text)
                else:
                    value[self.text_content] = self._fromstring(text)
        count = Counter(child.tag for child in children)
        for child in children:
            if count[child.tag] == 1:
                value.update(self.data(child))
            else:
                result = value.setdefault(child.tag, self.list())
                result += self.data(child).values()
        # if simple_text, elements with no children nor attrs become '', not {}
        if isinstance(value, dict) and not value and self.simple_text:
            value = ''
        return self.dict([(root.tag, value)])
567182
def load_xml_attrs(self):
        

        attrs_list = list()

        if hasattr(self, 'xml_element'):
            xml_attrs = self.xml_element.attrib

            for variable, value in iter(xml_attrs.items()):
                uri, tag = Element.get_namespace_and_tag(variable)
                tag = tag.replace('-', '_')
                attrs_list.append(tag)
                setattr(self, tag, value)

            self.attrs = attrs_list

        return self.attrs
627859
def convert_dict(obj, ids, parent, attr_type, item_func, cdata):
    """"""
    LOG.info('Inside convert_dict(): obj type is: "%s", obj="%s"' % (
        type(obj).__name__, unicode_me(obj))
    )
    output = []
    addline = output.append
    
    item_name = item_func(parent)
    
    for key, val in obj.items():
        LOG.info('Looping inside convert_dict(): key="%s", val="%s", type(val)="%s"' % (
            unicode_me(key), unicode_me(val), type(val).__name__)
        )

        attr = {} if not ids else {'id': '%s' % (get_unique_id(parent)) }

        key, attr = make_valid_xml_name(key, attr)

        if isinstance(val, numbers.Number) or type(val) in (str, unicode):
            addline(convert_kv(key, val, attr_type, attr, cdata))

        elif hasattr(val, 'isoformat'): # datetime
            addline(convert_kv(key, val.isoformat(), attr_type, attr, cdata))

        elif type(val) == bool:
            addline(convert_bool(key, val, attr_type, attr, cdata))

        elif isinstance(val, dict):
            if attr_type:
                attr['type'] = get_xml_type(val)
            addline('<%s%s>%s</%s>' % (
                key, make_attrstring(attr), 
                convert_dict(val, ids, key, attr_type, item_func, cdata), 
                key
                )
            )

        elif isinstance(val, collections.Iterable):
            if attr_type:
                attr['type'] = get_xml_type(val)
            addline('<%s%s>%s</%s>' % (
                key, 
                make_attrstring(attr), 
                convert_list(val, ids, key, attr_type, item_func, cdata), 
                key
                )
            )

        elif val is None:
            addline(convert_none(key, val, attr_type, attr, cdata))

        else:
            raise TypeError('Unsupported data type: %s (%s)' % (
                val, type(val).__name__)
            )

    return ''.join(output)
270358
def _parse_dict(element, definition):
    
    sub_dict = {}

    for name, subdef in viewitems(definition):
        (name, required) = _parse_name(name)

        sub_dict[name] = xml_to_json(element, subdef, required)

    return sub_dict
267954
def elementtree_to_dict(element):
    """"""
    d = dict()
    if hasattr(element, 'text') and element.text is not None:
        d['text'] = element.text

    d.update(element.items())  # element's attributes

    for c in list(element):  # element's children
        if c.tag not in d:
            d[c.tag] = elementtree_to_dict(c)
        # an element with the same tag was already in the dict
        else:
            # if it's not a list already, convert it to a list and append
            if not isinstance(d[c.tag], list):
                d[c.tag] = [d[c.tag], elementtree_to_dict(c)]
           # append to the list
            else:
                d[c.tag].append(elementtree_to_dict(c))
    return d
424036
def __convert(root, tag, values, func):
    
    elements = root.getElementsByTagName(tag)

    for element in elements:
        converted = func(element)

        # Append to the list
        __append_list(values, converted)
88601
def _xml_to_dict(self, element):
        
        return_dict = {}
        for el in element:
            return_dict[el.tag] = None
            children = el.getchildren()
            if children:
                return_dict[el.tag] = self._xml_to_dict(children)
            else:
                return_dict[el.tag] = el.text
        return return_dict
1072207
def xml(self, text=TEXT):
        
        def convert(line):
            xml = "  <item>\n"
            for f in line.index:
                xml += "    <field name=\"%s\">%s</field>\n" % (f, line[f])
            xml += "  </item>\n"
            return xml
        return "<items>\n" + '\n'.join(self._data.apply(convert, axis=1)) + \
               "</items>"
488064
def _add_meta_dict_to_xml(self, doc, parent, meta_dict):
        
        if not meta_dict:
            return
        key_list = list(meta_dict.keys())
        key_list.sort()
        for key in key_list:
            el_list = _index_list_of_values(meta_dict, key)
            for el in el_list:
                self._add_meta_value_to_xml_doc(doc, parent, el)
280749
def pydict2xmlstring(metadata_dict, **kwargs):
    """"""
    ordering = kwargs.get('ordering', UNTL_XML_ORDER)
    root_label = kwargs.get('root_label', 'metadata')
    root_namespace = kwargs.get('root_namespace', None)
    elements_namespace = kwargs.get('elements_namespace', None)
    namespace_map = kwargs.get('namespace_map', None)
    root_attributes = kwargs.get('root_attributes', None)
    # Set any root namespace and namespace map.
    if root_namespace and namespace_map:
        root = Element(root_namespace + root_label, nsmap=namespace_map)
    elif namespace_map:
        root = Element(root_label, nsmap=namespace_map)
    else:
        root = Element(root_label)
    # Set any root element attributes.
    if root_attributes:
        for key, value in root_attributes.items():
            root.attrib[key] = value
    # Create an XML structure from field list.
    for metadata_key in ordering:
        if metadata_key in metadata_dict:
            for element in metadata_dict[metadata_key]:
                if 'content' in element and 'qualifier' in element:
                    create_dict_subelement(
                        root,
                        metadata_key,
                        element['content'],
                        attribs={'qualifier': element['qualifier']},
                        namespace=elements_namespace,
                    )
                elif 'content' in element and 'role' in element:
                    create_dict_subelement(
                        root,
                        metadata_key,
                        element['content'],
                        attribs={'role': element['role']},
                        namespace=elements_namespace,
                    )
                elif 'content' in element and 'scheme' in element:
                    create_dict_subelement(
                        root,
                        metadata_key,
                        element['content'],
                        attribs={'scheme': element['scheme']},
                        namespace=elements_namespace,
                    )
                elif 'content' in element:
                    create_dict_subelement(
                        root,
                        metadata_key,
                        element['content'],
                        namespace=elements_namespace,
                    )
    # Create the XML tree.
    return '<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(
        root,
        pretty_print=True
    )
1365976
def get_specific_nodes(self, node, names):
        
        nodes = [(x.tagName, x) for x in node.childNodes
                 if x.nodeType == x.ELEMENT_NODE and
                 x.tagName in names]
        return dict(nodes)
53971
def parse_xml(self, node):
        
        import struct
        import array

        self._set_properties(node)
        data = None
        next_gid = None
        data_node = node.find('data')

        encoding = data_node.get('encoding', None)
        if encoding == 'base64':
            from base64 import b64decode

            data = b64decode(data_node.text.strip())

        elif encoding == 'csv':
            next_gid = map(int, "".join(
                line.strip() for line in data_node.text.strip()).split(","))

        elif encoding:
            msg = 'TMX encoding type: {0} is not supported.'
            logger.error(msg.format(encoding))
            raise Exception

        compression = data_node.get('compression', None)
        if compression == 'gzip':
            import gzip

            with gzip.GzipFile(fileobj=six.BytesIO(data)) as fh:
                data = fh.read()

        elif compression == 'zlib':
            import zlib

            data = zlib.decompress(data)

        elif compression:
            msg = 'TMX compression type: {0} is not supported.'
            logger.error(msg.format(compression))
            raise Exception

        # if data is None, then it was not decoded or decompressed, so
        # we assume here that it is going to be a bunch of tile elements
        # TODO: this will/should raise an exception if there are no tiles
        if encoding == next_gid is None:
            def get_children(parent):
                for child in parent.findall('tile'):
                    yield int(child.get('gid'))

            next_gid = get_children(data_node)

        elif data:
            if type(data) == bytes:
                fmt = struct.Struct('<L')
                iterator = (data[i:i + 4] for i in range(0, len(data), 4))
                next_gid = (fmt.unpack(i)[0] for i in iterator)
            else:
                msg = 'layer data not in expected format ({})'
                logger.error(msg.format(type(data)))
                raise Exception

        init = lambda: [0] * self.width
        reg = self.parent.register_gid

        # H (16-bit) may be a limitation for very detailed maps
        self.data = tuple(array.array('H', init()) for i in range(self.height))
        for (y, x) in product(range(self.height), range(self.width)):
            self.data[y][x] = reg(*decode_gid(next(next_gid)))

        return self
1090678
def generated_tag_data(tags):
    
    generated_tags = []
    for key, value in tags.items():
        generated_tags.append({
            'Key': key,
            'Value': value,
        })
    return generated_tags
538969
def create_node(xml_node: XmlNode, **init_args):
    ''''''
    inst_type = get_inst_type(xml_node)
    init_args['xml_node'] = xml_node
    inst = create_inst(inst_type, **init_args)
    if not isinstance(inst, Node):
        inst = convert_to_node(inst, **init_args)
    return inst