transxml.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. import os
  2. from json import loads
  3. from dicttoxml import dicttoxml
  4. from xml.dom.minidom import parseString
  5. def jsonToXml(json_path, xml_path):
  6. #@abstract: transfer json file to xml file
  7. #json_path: complete path of the json file
  8. #xml_path: complete path of the xml file
  9. with open(json_path, 'r', encoding='UTF-8') as json_file:
  10. load_dict = loads(json_file.read())
  11. my_item_func = lambda x: 'Annotation'
  12. xml = dicttoxml(load_dict, custom_root='Annotations', item_func=my_item_func, attr_type=False)
  13. dom = parseString(xml)
  14. with open(xml_path, 'w', encoding='UTF-8') as xml_file:
  15. xml_file.write(dom.toprettyxml())
  16. def json_to_xml(json_dir, xml_dir):
  17. # transfer all json file which in the json_dir to xml_dir
  18. if(os.path.exists(xml_dir)==False):
  19. os.makedirs(xml_dir)
  20. dir = os.listdir(json_dir)
  21. for file in dir:
  22. file_list=file.split(".")
  23. if(file_list[-1] == 'json'):
  24. jsonToXml(os.path.join(json_dir,file),os.path.join(xml_dir,file_list[0]+'.xml'))
  25. if __name__ == '__main__':
  26. #trandfer singal file
  27. j_path = "9-28-17.json"
  28. x_path = "9-28-17.xml"
  29. jsonToXml(j_path, x_path)