Python dicttoxml.dicttoxml() Examples

The following are 28 code examples of dicttoxml.dicttoxml(). 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 dicttoxml , or try the search function .
Example #1
Source File: xml.py    From recon-ng-marketplace with GNU General Public License v3.0 6 votes vote down vote up
def module_run(self):
        filename = self.options['filename']
        with codecs.open(filename, 'wb', encoding='utf-8') as outfile:
            # build a list of table names
            tables = [x.strip() for x in self.options['tables'].split(',')]
            data_dict = {}
            cnt = 0
            for table in tables:
                data_dict[table] = []
                columns = [x[0] for x in self.get_columns(table)]
                columns_str = '", "'.join(columns)
                rows = self.query(f'SELECT "{columns_str}" FROM "{table}" ORDER BY 1')
                for row in rows:
                    row_dict = {}
                    for i in range(0, len(columns)):
                        row_dict[columns[i]] = row[i]
                    data_dict[table].append(row_dict)
                    cnt += 1
            # write the xml to a file
            reparsed = parseString(dicttoxml(data_dict))
            outfile.write(reparsed.toprettyxml(indent=' '*4))
        self.output(f"{cnt} records added to '{filename}'.") 
Example #2
Source File: xml.py    From pentestly with GNU General Public License v3.0 6 votes vote down vote up
def module_run(self):
        filename = self.options['filename']
        with codecs.open(filename, 'wb', encoding='utf-8') as outfile:
            # build a list of table names
            tables = [x.strip() for x in self.options['tables'].split(',')]
            data_dict = {}
            cnt = 0
            for table in tables:
                data_dict[table] = []
                columns = [x[0] for x in self.get_columns(table)]
                rows = self.query('SELECT "%s" FROM "%s" ORDER BY 1' % ('", "'.join(columns), table))
                for row in rows:
                    row_dict = {}
                    for i in range(0,len(columns)):
                        row_dict[columns[i]] = row[i]
                    data_dict[table].append(row_dict)
                    cnt += 1
            # write the xml to a file
            reparsed = parseString(dicttoxml(data_dict))
            outfile.write(reparsed.toprettyxml(indent=' '*4))
        self.output('%d records added to \'%s\'.' % (cnt, filename)) 
Example #3
Source File: adapt_analysis.py    From adapt with Apache License 2.0 6 votes vote down vote up
def get_results(self):
		pathlib.Path('./output/').mkdir(parents=True, exist_ok=True) 
		if(self.output_format == "xml"):
			xml = dicttoxml(self.final_results, attr_type=False)
			f = open(self.output_file, "wb")
			f.write(xml)
			f.close()
		else:
			try:
				if(self.args["adapt_general"]["append"] == True and os.path.isfile(self.output_file)):
					with open(self.output_file, "r") as f:
						d = json.load(f)
						f.close()
						d += self.final_results
						self.final_results = d
				with open(self.output_file, "w") as f:
					json.dump(self.final_results, f, indent=4)
					f.close()
			except Exception as e:
				with open(self.backup, "w") as f:
					json.dump(self.final_results, f, indent=4)
					f.close() 
Example #4
Source File: adapt_analysis.py    From adapt with Apache License 2.0 6 votes vote down vote up
def get_results(self):
		pathlib.Path('./output/').mkdir(parents=True, exist_ok=True) 
		if(self.output_format == "xml"):
			xml = dicttoxml(self.final_results, attr_type=False)
			f = open(self.output_file, "wb")
			f.write(xml)
			f.close()
		else:
			try:
				if(self.args["adapt_general"]["append"] == True and os.path.isfile(self.output_file)):
					with open(self.output_file, "r") as f:
						d = json.load(f)
						f.close()
						d += self.final_results
						self.final_results = d
				with open(self.output_file, "w") as f:
					json.dump(self.final_results, f, indent=4)
					f.close()
			except Exception as e:
				with open(self.backup, "w") as f:
					json.dump(self.final_results, f, indent=4)
					f.close() 
Example #5
Source File: renderers.py    From kpi with GNU Affero General Public License v3.0 6 votes vote down vote up
def render(self, data, accepted_media_type=None, renderer_context=None):

        # data should be str, but in case it's a dict, return as XML.
        # e.g. It happens with 404
        if isinstance(data, dict):
            # Force cast `ErrorDetail` as `six.text_type` because `dicttoxml`
            # does not recognize this type and treat each character as xml node.
            for k, v in data.items():
                if isinstance(v, ErrorDetail):
                    data[k] = str(v)

            # FIXME new `v2` list endpoint enters this block
            # Submissions are wrapped in `<item>` nodes.
            return dicttoxml(data, attr_type=False)

        if renderer_context.get("view").action == "list":
            return "<root>{}</root>".format("".join(data))
        else:
            return data 
Example #6
Source File: markup.py    From rupo with Apache License 2.0 6 votes vote down vote up
def to_xml(self) -> str:
        """
        Экспорт в XML.

        :return self: строка в формате XML
        """
        return dicttoxml(self.to_dict(), custom_root='markup', attr_type=False).decode('utf-8').replace("\n", "\\n") 
Example #7
Source File: plugin_jsontoxml.py    From deen with Apache License 2.0 6 votes vote down vote up
def process(self, data):
        super(DeenPluginJsonToXmlFormatter, self).process(data)
        if not DICTTOXML:
            return
        try:
            data = json.loads(data.decode())
        except (json.JSONDecodeError, TypeError,
                UnicodeDecodeError, AssertionError) as e:
            self.error = e
            self.log.error(self.error)
            self.log.debug(self.error, exc_info=True)
            return
        try:
            data = dicttoxml.dicttoxml(data)
        except Exception as e:
            self.error = e
            self.log.error(self.error)
            self.log.debug(self.error, exc_info=True)
        return data 
Example #8
Source File: xml.py    From recon-ng with GNU General Public License v3.0 6 votes vote down vote up
def module_run(self):
        filename = self.options['filename']
        with codecs.open(filename, 'wb', encoding='utf-8') as outfile:
            # build a list of table names
            tables = [x.strip() for x in self.options['tables'].split(',')]
            data_dict = {}
            cnt = 0
            for table in tables:
                data_dict[table] = []
                columns = [x[0] for x in self.get_columns(table)]
                rows = self.query('SELECT "%s" FROM "%s" ORDER BY 1' % ('", "'.join(columns), table))
                for row in rows:
                    row_dict = {}
                    for i in range(0,len(columns)):
                        row_dict[columns[i]] = row[i]
                    data_dict[table].append(row_dict)
                    cnt += 1
            # write the xml to a file
            reparsed = parseString(dicttoxml(data_dict))
            outfile.write(reparsed.toprettyxml(indent=' '*4))
        self.output('%d records added to \'%s\'.' % (cnt, filename)) 
Example #9
Source File: xml.py    From EasY_HaCk with Apache License 2.0 6 votes vote down vote up
def module_run(self):
        filename = self.options['filename']
        with codecs.open(filename, 'wb', encoding='utf-8') as outfile:
            # build a list of table names
            tables = [x.strip() for x in self.options['tables'].split(',')]
            data_dict = {}
            cnt = 0
            for table in tables:
                data_dict[table] = []
                columns = [x[0] for x in self.get_columns(table)]
                rows = self.query('SELECT "%s" FROM "%s" ORDER BY 1' % ('", "'.join(columns), table))
                for row in rows:
                    row_dict = {}
                    for i in range(0,len(columns)):
                        row_dict[columns[i]] = row[i]
                    data_dict[table].append(row_dict)
                    cnt += 1
            # write the xml to a file
            reparsed = parseString(dicttoxml(data_dict))
            outfile.write(reparsed.toprettyxml(indent=' '*4))
        self.output('%d records added to \'%s\'.' % (cnt, filename)) 
Example #10
Source File: voltha_rpc.py    From voltha with Apache License 2.0 5 votes vote down vote up
def execute(self):
        if self.rpc_response.is_error:
            returnValue(self.rpc_response)

        log.info('voltha-rpc-request', session=self.session.session_id,
                 request=self.request)

        # Execute the request
        res_dict, yang_options = yield self.grpc_client.invoke_voltha_rpc(
            service=self.service,
            method=self.method,
            params=self.request['params'],
            metadata=self.metadata)

        # convert dict to xml
        xml = dicttoxml.dicttoxml(res_dict, attr_type=True)
        log.info('voltha-info', res=res_dict, xml=xml)

        root_elem = self.get_root_element(xml)

        # Build the yang response
        self.rpc_response.node = self.rpc_response.build_yang_response(
            root_elem, self.request, yang_options=yang_options, custom_rpc=True)
        self.rpc_response.is_error = False

        returnValue(self.rpc_response) 
Example #11
Source File: plugin_jsontoxml.py    From deen with Apache License 2.0 5 votes vote down vote up
def prerequisites(self):
        try:
            import dicttoxml
        except ImportError:
            self.log_missing_depdendencies('dicttoxml')
            return False
        else:
            return True 
Example #12
Source File: pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def __json_to_xml(self, json_input):
        from dicttoxml import dicttoxml

        xml = dicttoxml(
            json_input,
            custom_root="request",
            attr_type=False,
            item_func=lambda x: "article",
        )
        return xml.decode("utf-8") 
Example #13
Source File: exports.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
def xmlify(rows):
    '''Expects a list of dictionaries and returns a XML response.'''
    xml = dicttoxml(rows)
    return Response(xml, mimetype='text/xml') 
Example #14
Source File: utils.py    From grest with GNU General Public License v3.0 5 votes vote down vote up
def serialize(data):
    try:
        accept = get_header(global_config.ACCEPT)

        if accept == "application/json":
            return jsonify(data)
        elif accept == "text/yaml":
            return yaml.safe_dump(data)
        elif accept == "text/xml":
            return dicttoxml.dicttoxml(data)
        else:
            # return json if content-type is not set
            return jsonify(data)
    except Exception:
        return jsonify(errors=[msg.SERIALIZATION_EXCEPTION]), 500 
Example #15
Source File: util.py    From addon-pyone with Apache License 2.0 5 votes vote down vote up
def cast2one(param):

    '''
    This function will cast parameters to make them nebula friendly
    flat dictionaries will be turned into attribute=value vectors
    dictionaries with root dictionary will be serialized as XML
    Structures will be turned into strings before being submitted.

    :param param: the parameter to make nebula friendly
    :return: casted parameter
    '''

    if isinstance(param, IntEnum):
        # if the param is a constant we return its value
        return param.value
    if isinstance(param, dict):
        # if this is a structured type
        # in case we passed a dictionary that is part of another
        if hasattr(param, '_root'):
            param = param._root
        # if the dictionary is not empty
        if bool(param):
            root = list(param.values())[0]
            if isinstance(root, dict):
                # We return this dictionary as XML
                return dicttoxml.dicttoxml(param, root=False, attr_type=False).decode('utf8')
            else:
                # We return this dictionary as attribute=value vector
                ret = u""
                for (k, v) in param.items():
                    ret = u'''%s%s="%s"\n''' % (ret, k, v)
                return ret
        else:
            raise Exception("Cannot cast empty dictionary")
    else:
        return param 
Example #16
Source File: Connection.py    From huawei-lte-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _create_request_xml(data: Union[dict, list], dicttoxml_xargs: Optional[dict]=None) -> bytes:
        if not dicttoxml_xargs:
            dicttoxml_xargs = {}

        dicttoxml_xargs['attr_type'] = False
        return dicttoxml.dicttoxml(data, custom_root='request', **dicttoxml_xargs) 
Example #17
Source File: formatter.py    From pygreynoise with MIT License 5 votes vote down vote up
def xml_formatter(result, _verbose):
    """Format result as xml."""
    return parseString(dicttoxml(result)).toprettyxml() 
Example #18
Source File: __init__.py    From xmindparser with MIT License 5 votes vote down vote up
def xmind_to_xml(file_path):
    try:
        from dicttoxml import dicttoxml
        from xml.dom.minidom import parseString
        target = _get_out_file_name(file_path, 'xml')
        xml = dicttoxml(xmind_to_dict(file_path), custom_root='root')
        xml = parseString(xml.decode('utf8')).toprettyxml(encoding='utf8')

        with open(target, 'w', encoding='utf8') as f:
            f.write(xml.decode('utf8'))

        return target
    except ImportError:
        raise ImportError('Parse xmind to xml require "dicttoxml", try install via pip:\n' +
                          '> pip install dicttoxml') 
Example #19
Source File: xml_export_formatter.py    From exporters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def format(self, item):
        import dicttoxml
        dicttoxml.LOG.setLevel(logging.WARNING)
        fields_len = len(self.fields_order)
        ordered_item = collections.OrderedDict(
            sorted(item.items(),
                   key=lambda kv: self.fields_order.get(kv[0], fields_len))
        )
        return '<{0}>{1}</{0}>'.format(
            self.item_name, dicttoxml.dicttoxml(ordered_item, root=False,
                                                attr_type=self.attr_type)) 
Example #20
Source File: cos_comm.py    From cos-python-sdk-v5 with MIT License 5 votes vote down vote up
def format_xml(data, root, lst=list(), parent_child=False):
    """将dict转换为xml, xml_config是一个bytes"""
    if parent_child:
        xml_config = dicttoxml(data, item_func=lambda x: x[:-1], custom_root=root, attr_type=False)
    else:
        xml_config = dicttoxml(data, item_func=lambda x: x, custom_root=root, attr_type=False)
    for i in lst:
        xml_config = xml_config.replace(to_bytes(i+i), to_bytes(i))
    return xml_config 
Example #21
Source File: response.py    From assembly with MIT License 5 votes vote down vote up
def xml(func):
    """
    Decorator to render as XML
    :param func:
    :return:
    """
    if inspect.isclass(func):
        apply_function_to_members(func, xml)
        return func
    else:
        @functools.wraps(func)
        def decorated_view(*args, **kwargs):
            data = func(*args, **kwargs)
            return _build_response(data, dicttoxml)
        return decorated_view 
Example #22
Source File: exports.py    From recon-ng with GNU General Public License v3.0 5 votes vote down vote up
def xmlify(rows):
    '''Expects a list of dictionaries and returns a XML response.'''
    xml = dicttoxml([dict(r) for r in rows])
    return Response(xml, mimetype='text/xml') 
Example #23
Source File: dict_to_xml.py    From python-tools with MIT License 5 votes vote down vote up
def dict_to_xml(dict):
    """Convert dict to xml.

    Args:
        dict (dict): Dictionary.

    Returns:
        str: Return a XML representation of an dict.

    """
    return dicttoxml(dict).decode() 
Example #24
Source File: unite.py    From PoetryCorpus with Apache License 2.0 5 votes vote down vote up
def to_xml(self, filename):
        with open(filename, 'wb') as f:
            f.write(b'<?xml version="1.0" encoding="UTF-8"?><items>')
            for element in self.data:
                xml = dicttoxml(element, custom_root='item', attr_type=False)\
                    .replace(b'<?xml version="1.0" encoding="UTF-8" ?>', b'')
                f.write(xml)
            f.write(b'</items>') 
Example #25
Source File: server.py    From query-server with Apache License 2.0 5 votes vote down vote up
def bad_request(error):
    message = {'Error': error[1], 'Status Code': error[0]}
    response = dicttoxml(message) if error[2] == 'xml' else json.dumps(message)
    return make_response(response, error[0]) 
Example #26
Source File: sipcreator.py    From IFIscripts with MIT License 4 votes vote down vote up
def process_dcp(sip_path, content_title, args, new_manifest_textfile, new_log_textfile, metadata_dir, clairmeta_version):
    '''
    Runs DCP specific functions.
    '''
    objects_dir = os.path.join(sip_path, 'objects')
    cpl = ififuncs.find_cpl(objects_dir)
    dcp_dirname = os.path.dirname(cpl)
    os.chdir(os.path.dirname(dcp_dirname))
    os.rename(os.path.basename(dcp_dirname), content_title)
    new_dcp_path = os.path.join('objects', content_title).replace("\\", "/")
    absolute_dcp_path = os.path.join(sip_path, new_dcp_path)
    ififuncs.manifest_replace(
        new_manifest_textfile,
        os.path.join('objects', os.path.basename(args.i[0])).replace("\\", "/"),
        new_dcp_path
    )
    '''
    a = subprocess.check_output(['python', '-m', 'clairmeta.cli', 'check', '-type', 'dcp', absolute_dcp_path], stderr=subprocess.STDOUT)
    b = subprocess.check_output(['python', '-m', 'clairmeta.cli', 'probe', '-type', 'dcp', '-format', 'xml', absolute_dcp_path], stderr=subprocess.STDOUT)
    '''
    dcp = DCP(absolute_dcp_path)
    dcp_dict = dcp.parse()
    # json_str = json.dumps(dcp_dict , sort_keys=True, indent=2, separators=(',', ': '))
    xml_str = dicttoxml.dicttoxml(dcp_dict, custom_root='ClairmetaProbe', ids=False, attr_type=False)
    xml_pretty = prettyprint_xml(xml_str)
    status, report = dcp.check()
    ififuncs.generate_log(
        new_log_textfile,
        'EVENT = eventType=validation, eventOutcome=%s, eventDetail=%s, agentName=Clairmeta version %s' % (
            status, report, clairmeta_version
        )
    )
    clairmeta_xml = os.path.join(metadata_dir, '%s_clairmeta.xml' % content_title)
    ififuncs.generate_log(
        new_log_textfile,
        'EVENT = Metadata extraction - eventDetail=Clairmeta DCP metadata extraction, eventOutcome=%s, agentName=Clairmeta version %s' % (clairmeta_xml, clairmeta_version)
    )
    with open(clairmeta_xml, 'w') as fo:
        fo.write(xml_pretty)
    ififuncs.checksum_replace(new_manifest_textfile, new_log_textfile, 'md5')
    ififuncs.manifest_update(new_manifest_textfile, clairmeta_xml)
    print(status)
    print(report) 
Example #27
Source File: server.py    From query-server with Apache License 2.0 4 votes vote down vote up
def search(search_engine):
    try:
        count = int(request.args.get('num', 10))
        qformat = request.args.get('format', 'json').lower()
        qtype = request.args.get('type', '')
        if qformat not in ('json', 'xml', 'csv'):
            abort(400, 'Not Found - undefined format')

        engine = search_engine
        if engine not in scrapers:
            error = [404, 'Incorrect search engine', engine]
            return bad_request(error)

        query = request.args.get('query')
        if not query:
            error = [400, 'Not Found - missing query', qformat]
            return bad_request(error)

        # first see if we can get the results for the cache
        engine_and_query = engine + ':' + query
        result = lookup(engine_and_query)
        if result:
            print("cache hit: {}".format(engine_and_query))
        else:
            result = feed_gen(query, engine, count, qtype)
            if result:
                # store the result in the cache to speed up future searches
                store(engine_and_query, result)
            else:
                error = [404, 'No response', engine_and_query]
                return bad_request(error)

        try:
            unicode  # unicode is undefined in Python 3 so NameError is raised
            for line in result:
                line['link'] = line['link'].encode('utf-8')
                if 'title' in line:
                    line['title'] = line['title'].encode('utf-8')
                if 'desc' in line:
                    line['desc'] = line['desc'].encode('utf-8')
        except NameError:
            pass  # Python 3 strings are already Unicode
        if qformat == 'json':
            return jsonify(result)
        elif qformat == 'csv':
            csvfeed = '"'
            csvfeed += '","'.join(result[0].keys())
            for line in result:
                csvfeed += '"\n"'
                csvfeed += '","'.join(line.values())
            csvfeed += '"'
            return Response(csvfeed)

        xmlfeed = dicttoxml(result, custom_root='channel', attr_type=False)
        xmlfeed = parseString(xmlfeed).toprettyxml()
        return Response(xmlfeed, mimetype='application/xml')
    except Exception as e:
        print(e)
        return jsonify(errorObj) 
Example #28
Source File: get.py    From voltha with Apache License 2.0 4 votes vote down vote up
def execute(self):
        if self.rpc_response.is_error:
            returnValue(self.rpc_response)

        log.info('get-request', session=self.session.session_id,
                 request=self.request)

        rpc = self.get_voltha_rpc(self.request)
        if not rpc:
            log.info('unsupported-request', request=self.request)
            self.rpc_response.is_error = True
            self.rpc_response.node = ncerror.NotImpl(self.request_xml)
            returnValue(self.rpc_response)

        # Extract the service and method name from the rpc
        command = rpc.split('-')
        if len(command) != 2:
            log.debug('unsupported-rpc', rpc=rpc)
            self.rpc_response.is_error = True
            self.rpc_response.node = ncerror.NotImpl(self.request_xml)
            returnValue(self.rpc_response)

        self.service = command[0]
        self.method = command[1]
        self.params = {}
        if self.request.has_key('metadata'):
            self.metadata = self.request['metadata']

        # Execute the request
        res_dict, yang_options = yield self.grpc_client.invoke_voltha_rpc(
            service=self.service,
            method=self.method,
            params=self.params,
            metadata=self.metadata)

        # convert dict to xml
        xml = dicttoxml.dicttoxml(res_dict, attr_type=True)
        log.info('voltha-info', res=res_dict, xml=xml)

        root_elem = self.get_root_element(xml)

        # Build the yang response
        self.rpc_response.node = self.rpc_response.build_yang_response(
            root_elem, self.request, yang_options=yang_options)
        self.rpc_response.is_error = False

        returnValue(self.rpc_response)