r"""Convert python object to xml string.

        :param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
        :rtype: str or unicode

        .. versionadded:: 1.2
770514
def object2xml(self, data):
        
        """
        if not self.__options['encoding']:
            self.set_options(encoding=self.__encoding)

        if self.__options['header_declare']:
            self.__tree.append(self.build_xml_header())

        root = self.__options['root']
        if not root:
            assert (isinstance(data, utils.DictTypes) and len(data) == 1), \
                'if root not specified, the data that dict object and length must be one required.'
            root, data = data.items()[0]

        self.build_tree(data, root)
        xml = unicode(''.join(self.__tree).strip())

        if self.__options['encoding'] != self.__encoding:
            xml = xml.encode(self.__options['encoding'], errors=self.__options['errors'])
        return xml
159151
def from_dict(self, data):
        
        if "model" in data:
            model = data["model"]
            self.description = model["description"] if "description" in model else None
            self.package = model["package"] if "package" in model else None
            self.extends = model["extends"] if "extends" in model else []
            self.entity_name = model["entity_name"] if "entity_name" in model else None
            self.rest_name = model["rest_name"] if "rest_name" in model else None
            self.resource_name = model["resource_name"] if "resource_name" in model else None
            self.allows_get = model["get"] if "get" in model else False
            self.allows_create = model["create"] if "create" in model else False
            self.allows_update = model["update"] if "update" in model else False
            self.allows_delete = model["delete"] if "delete" in model else False
            self.is_root = model["root"] if "root" in model else False
            self.userlabel = model["userlabel"] if "userlabel" in model else None
            self.template = model["template"] if "template" in model else False
            self.allowed_job_commands = model["allowed_job_commands"] if "allowed_job_commands" in model else None

        if "attributes" in data:
            self.attributes = self._get_attributes(data["attributes"])

        if "children" in data:
            self.child_apis = self._get_apis(data["children"])
464233
def to_xml(xml_builder)
      attributes = {
          'metadata:type' => type,
      }

      if value.nil?
        attributes['metadata:null'] = 'true'
        xml_builder['data'].send(name.to_sym, attributes)
      else
        xml_builder['data'].send(name.to_sym, attributes, xml_value)
      end
    end
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
1092612
def to_xml(body_element):
    
    doctype = b"""<?xml version="1.0" encoding="UTF-8"?>\n"""
    if body_element is None:
        return succeed(b"")
    d = flattenString(None, body_element)
    d.addCallback(lambda flattened: doctype + flattened)
    return d
566167
def get_xml(self, encoding='unicode'):
        
        return xml.etree.ElementTree.tostring(self._root_el, encoding)
900632
def _xml_convert(self, element):
        

        children = list(element)

        if len(children) == 0:
            return self._type_convert(element.text)
        else:
            # if the fist child tag is list-item means all children are list-item
            if children[0].tag == "list-item":
                data = []
                for child in children:
                    data.append(self._xml_convert(child))
            else:
                data = {}
                for child in children:
                    data[child.tag] = self._xml_convert(child)

            return data
1298300
def XML_fromstring(content, source=None):
    
    try:
        tree = ET.fromstring(content)
    except ET.ParseError as err:
        x_parse_error(err, content, source)
    return tree
1366836
def serialize_to_string(
        root_processor,  # type: RootProcessor
        value,  # type: Any
        indent=None  # type: Optional[Text]
):
    # type: (...) -> Text
    
    if not _is_valid_root_processor(root_processor):
        raise InvalidRootProcessor('Invalid root processor')

    state = _ProcessorState()
    state.push_location(root_processor.element_path)

    root = root_processor.serialize(value, state)

    state.pop_location()

    # Always encode to UTF-8 because element tree does not support other
    # encodings in earlier Python versions. See: https://bugs.python.org/issue1767933
    serialized_value = ET.tostring(root, encoding='utf-8')

    # Since element tree does not support pretty printing XML, we use minidom to do the pretty
    # printing
    if indent:
        serialized_value = minidom.parseString(serialized_value).toprettyxml(
            indent=indent, encoding='utf-8'
        )

    return serialized_value.decode('utf-8')
19167
def data_element_tree_to_string(data_element):
    
    # FIXME: rewrite this as a visitor to use the data element tree traverser.
    def __dump(data_el, stream, offset):
        name = data_el.__class__.__name__
        stream.write("%s%s" % (' ' * offset, name))
        offset += 2
        ifcs = provided_by(data_el)
        if ICollectionDataElement in ifcs:
            stream.write("[")
            first_member = True
            for member_data_el in data_el.get_members():
                if first_member:
                    stream.write('%s' % os.linesep + ' ' * offset)
                    first_member = False
                else:
                    stream.write(',%s' % os.linesep + ' ' * offset)
                __dump(member_data_el, stream, offset)
            stream.write("]")
        else:
            stream.write("(")
            if ILinkedDataElement in ifcs:
                stream.write("url=%s, kind=%s, relation=%s" %
                             (data_el.get_url(), data_el.get_kind(),
                              data_el.get_relation()))
            else:
                first_attr = True
                for attr_name, attr_value in iteritems_(data_el.data):
                    if first_attr:
                        first_attr = False
                    else:
                        stream.write(',%s' % os.linesep
                                     + ' ' * (offset + len(name) + 1))
                    if attr_value is None:
                        continue
                    if not IResourceDataElement in provided_by(attr_value):
                        stream.write("%s=%s" % (attr_name, attr_value))
                    else:
                        stream.write("%s=" % attr_name)
                        __dump(attr_value, stream, offset)
            stream.write(')')
    stream = NativeIO()
    __dump(data_element, stream, 0)
    return stream.getvalue()
1254200
def convert(data):
    
    try:
        st = basestring
    except NameError:
        st = str
    if isinstance(data, st):
        return str(data)
    elif isinstance(data, Mapping):
        return dict(map(convert, data.iteritems()))
    elif isinstance(data, Iterable):
        return type(data)(map(convert, data))
    else:
        return data
932482
def to_string(xml, **kwargs):
        

        if isinstance(xml, OneLogin_Saml2_XML._text_class):
            return xml

        if isinstance(xml, OneLogin_Saml2_XML._element_class):
            OneLogin_Saml2_XML.cleanup_namespaces(xml)
            return OneLogin_Saml2_XML._unparse_etree(xml, **kwargs)

        raise ValueError("unsupported type %r" % type(xml))
540293
def to_xml(data)
      ox = XML::Node.new(ox_tag)
      wrappers = {}
      
      ox_elems.each do |elem|
        if elem.in
          wrappers[elem.in] ||= XML::Node.new elem.in
          elem.to_xml(data).each {|e| wrappers[elem.in] << e}
        else
          elem.to_xml(data).each {|e| ox << e}
        end
      end
      
      wrappers.each {|k,v| ox << v}
      
      ox_attrs.each do |a| 
        val = data.send(a.accessor).to_s
        ox[a.tag]= val if val.present?
      end
      
      ox
    end
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", ''))
303948
def to_xml(self, xml_declaration=True):
        
        xml = ET.tostring(self.xml()).decode('utf-8')
        return '<?xml version="1.0" encoding="UTF-8"?>{}'.format(xml) if xml_declaration else xml
244058
def get_xml(self):
        
        with io.StringIO() as string:
            string.write(ET.tostring(self.root, encoding="unicode"))
            return string.getvalue()
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