from basic_config_vars.config_vars import moviesAllFilePath,moviesFilePath #自定义的一些文件变量import xmltodictimport jsonimport osimport tracebackclass XmlDict(): def __init__(self): pass #初始化数据,传入参数1、xml文件路径 2、xml格式字符串 3、json字符串 4、dict字典 def init_data(self,file_Str_Dict): if isinstance(file_Str_Dict,str) and os.path.isfile(file_Str_Dict): with open(file_Str_Dict) as fp: self.data=fp.read() elif isinstance(file_Str_Dict,(str,dict)): self.data=file_Str_Dict def xml_to_dict(self,file_Str_Dict): self.init_data(file_Str_Dict) data_orderedD=xmltodict.parse(self.data) data_json=json.dumps(data_orderedD,indent=4) data_dict=json.loads(data_json) return data_dict def dicttoxml(self,file_Str_Dict): self.init_data(file_Str_Dict) if isinstance(self.data,str): try: self.data=json.loads(self.data) except: print('传入参数非json或dict类型,无法转换。') traceback.print_exc() return None return xmltodict.unparse(self.data,pretty=True,encoding='gb2312')if __name__=='__main__': #obj=XmlDict(moviesFilePath) obj = XmlDict() d=obj.xml_to_dict(moviesAllFilePath) print(d) print('*'*30) #print(obj.dicttoxml(json.dumps(d))) print(obj.dicttoxml('{"nihao":{"ty":"leixing","fuoran":"feichang"}}')) print('hahaha')
XMl文件参考:
War, Thriller DVD 2003 PG 10 Talk about a US-Japan war Anime, Science Fiction DVD 1989 R 8 A schientific fiction Anime, Action DVD 4 PG 10 Vash the Stampede! Comedy VHS PG 2 Viewable boredom