合并dicttoxml json转储到一个xml文件

时间:2019-01-25 10:42:57

标签: python json xml merge dicttoxml

我有一些代码从服务器命令中获取一个input.xml文件,并且得到了output.xml
Bu我需要检查两台服务器并为此做一个循环,然后检查它,但是我只得到output.xml文件中的最后一个结果。 我需要将json.dumps(data)合并到一个字典或xmltodict生成的任何内容中,然后解析为一个xml。

我尝试了一些字典更新,但是没有用。

代码在这里:

def get_output_dict():    
    if vendor == 'HP':    
        data = xml_to_dict(xml_doc='hp_input.xml')  
    elif vendor == 'Dell':
        data = xml_to_dict(xml_doc='dell_input.xml')          
    for test in data['platform']['vendor']['tests']:
        command = test.get('command') #continue if command is not present
        output = remote(command)
        str1 = ''.join(str(e) for e in output)

    for key in test.keys():
      if key == 'command':
         test[key] = str1
         #Change command key name with result using .pop
         test['Result'] = test.pop('command')

     return json.loads(json.dumps(data))

def get_output_xml(output_dict):
    #dicttoxml.set_debug()
    output_xml =   dicttoxml.dicttoxml(output_dict,custom_root='output',attr_type=False,root=False)
    if vendor == 'HP':
        filename = 'hp_output-{}.xml'.format(host)
    elif vendor == 'Dell':
        filename = 'dell_output-{}.xml'.format(host)
    tree = etree.fromstring(output_xml)
    output_xml_string = etree.tostring(tree, pretty_print=True)        
    with open(filename, 'wb') as f:
        f.write(output_xml_string)
    print('Output for hostname server: {} written to:    
    {}'.format(host,filename))        
    return output_xml

for x in range(3, len(sys.argv)):
    print("Checking Server: %s" % (sys.argv[x]))
    remote = myssh(sys.argv[x], username, password)
    data = get_output_dict()
    xml = get_output_xml(data)

结果应该是,我在get_output_xml(data)处获取了来自两台服务器的两次迭代的合并数据,也许以后也可以在三台服务器上进行合并。

0 个答案:

没有答案