40 - xml文档与字典之间的互相转换

网友投稿 630 2022-11-02

40 - xml文档与字典之间的互相转换

40 - xml文档与字典之间的互相转换

1. 如何将一个字典转换为xml文档,并将该xml文档保存成文本文件

'''dicttoxmlpip install dicttixml'''import dicttoxmlfrom xml.dom.minidom import parseStringd = [20, 'names', {'name': 'Bill', 'age': '30', 'salary': 2000}, {'name': 'Mike', 'age': '20', 'salary': 3000}, {'name': 'John', 'age': '40', 'salary': 4000}]bxml = dicttoxml.dicttoxml(d, custom_root='persons')xml = bxml.decode('utf-8')print(xml)dom = parseString(xml)prettyxml = dom-rettyxml(indent=' ')print(prettyxml)f = open('persons1.xml', 'w', encoding='utf-8')f.write(prettyxml)f.close()

20namesBill302000Mike203000John404000 20 names Bill 30 2000 Mike 20 3000 John 40 4000

20 names Bill 30 2000 Mike 20 3000 John 40 4000

2. 如何读取xml文档的内容,并将其转换为字典

'''xmltodictpip install xmltodict'''import xmltodictf = open('products.xml', 'rt', encoding='utf-8')xml = f.read()import pprintd = xmltodict.parse(xml)print(d)pp = pprint.PrettyPrinter(indent=4)pp.pprint(d)print(type(d))

OrderedDict([('root', OrderedDict([('products', OrderedDict([('product', [OrderedDict([('@uuid', '1234'), ('id', '10000'), ('name', 'iphone9'), ('price', '9999')]), OrderedDict([('@uuid', '4321'), ('id', '20000'), ('name', '特斯拉'), ('price', '800000')]), OrderedDict([('@uuid', '5678'), ('id', '30000'), ('name', 'Mac Pro'), ('price', '40000')])])]))]))])OrderedDict([ ( 'root', OrderedDict([ ( 'products', OrderedDict([ ( 'product', [ OrderedDict([ ( '@uuid', '1234'), ( 'id', '10000'), ( 'name', 'iphone9'), ( 'price', '9999')]), OrderedDict([ ( '@uuid', '4321'), ( 'id', '20000'), ( 'name', '特斯拉'), ( 'price', '800000')]), OrderedDict([ ( '@uuid', '5678'), ( 'id', '30000'), ( 'name', 'Mac ' 'Pro'), ( 'price', '40000')])])]))]))])

​​41 - 将json字符串转换为类的实例​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Swift编写的iOS端和服务器端, 服务器端基于Perfect框架
下一篇:jmeter添加自定义扩展函数之图片base64编码示例详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~