import xmltodict
import json
import dicttoxml
"""
XML转化为JSON格式
安装xmltodict
pip install xmltodict
"""
def xmlTojson():
with open('11.xml', 'r', encoding='utf-8') as r:
xml_str = r.read()
# print(xml_str)
xml_parse = xmltodict.parse(xml_str)
print(xml_parse)
# o = xmltodict.parse('<e> \n<a>text</a>\n <a>text</a> \n</e>')
s = json.dumps(xml_parse) # '{"e": {"a": ["text", "text"]}}'
r = json.loads(s)
with open('111.json', 'w', encoding='utf-8') as w:
w.write(s)
# d = r.get('root').get('item')
# for i in d:
# print(i)
xmlTojson()
"""
JSON转化为XML格式
安装dicttoxml
pip install dicttoxml
"""
def jsonToxml():
lis = ['张三', '李四', '王五', '赵六']
xml_dic = []
for i in range(len(lis)):
dic = {
'id': '{}'.format(i + 1),
'name': '{}'.format(lis[i]),
}
xml_dic.append(dic)
"""
使用dicttoxml转化的xml中默认会在最外面包含一个<root> ... </root>,
使用参数root=False可以去掉这个东西。
同时默认的xml中还会包含每个属性的类型,就像<item type="str">,使用参数attr_type=False可以去掉这个东西。
"""
# xml = dicttoxml.dicttoxml(xml_dic, root=False, attr_type=False).decode('utf-8')
xml = dicttoxml.dicttoxml(xml_dic).decode('utf-8')
with open('111.xml', 'w', encoding='utf-8') as w:
w.write(xml)
print(xml)
# jsonToxml()