python3 xml_to_dict、dict_to_xml等互相转换的方法
from basic_config_vars.config_vars import moviesAllFilePath,moviesFilePath #自定义的一些文件变量 import xmltodict import json import os import traceback class 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文件参考:
<collection shelf="New Arrivals"> <movie title="Enemy Behind"> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> <movie title="Transformers"> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title="Trigun"> <type>Anime, Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description> </movie> <movie title="Ishtar"> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description> </movie> </collection>