xml转json?猛一听是不是挺蛋疼的,都是结构化数据的格式有这转换的必要么?是的,其实我也觉得无聊,不过手痒痒,总想来试试。网上也能找到一款名为xmltodict的转换工具,也挺好用的。我的方法如下,原理很简单,代码也很短。
xml文件:testXml.xml
<?xml version="1.0" encoding="utf-8"?>
<root>
<person age="18">
<name>张三</name>
<sex>男</sex>
</person>
<person age="19" des="您好">
<name>李四</name>
<sex>女</sex>
</person>
</root>
Python代码:
from xml.etree import ElementTree as et;
import json
#从xml文件读取结点 转换为json格式,并保存到文件中
print('read node from xmlfile, transfer them to json, and save into jsonFile:')
root=et.parse("testXml.xml");
f=open('testJson.json','a',encoding="utf8");
for each in root.getiterator("person"):
tempDict=each.attrib
for childNode in each.getchildren():
tempDict[childNode.tag]=childNode.text
tempJson=json.dumps(tempDict,ensure_ascii=False)
print(tempJson)
f.write(tempJson+"\n");
f.close()
#从json文件中读取,并打印
print('read json from jsonfile:')
for eachJson in open('testJson.json','r',encoding='utf8'):
tempStr=json.loads(eachJson);
print(tempStr)
结果如下: