立即学习:https://edu.csdn.net/course/play/26755/340151?utm_source=blogtoedu
题一:如何将一个字典转换为XML文档,并将该XML文档保存成文本文件
dicttoxml
pip install dicttoxml
import dicttoxml
import oa
from xml.dom.minidom import parseString
d = [20,'name',{'name':'Bill','age'
:30,'salary':2000},{'name':'Mike','age':'40','salary':3000},
{'name':'John,'age'
:20,'salary':1000}]
bxml = dicttoxml.dicttoxml(d,custom_root = 'persons')
xml = bxml.decode('utf-8')
print(xml)
dom = paseString(xml)
prettyxml = dom.toprettyxml(indent= ' ')
print(prettyxml)
f = open('file/persons1.xml','w',encoding='utf-8')
f.write(prettyxml)
f.close()
题二:如何读取XML文件的内容,并将其转换为字典
pip install xmltodict
import xmldict
f = open('files/products.xml','rt',enconding='utf-8')
xml = f.read()
import pprint
d = xmltodict.parse(xml)
print(d)
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(d)
print(type(d))
总结:需要2个第三方模块(需安装)
1.dicttoxml用于将字典转换为xml文档
2.xmltodict用于将xml文档转化为字典