使用到json库和xmltodict模块
import json
import xmltodict
filePath='D:\PycharmProjects\Python\ChinaCity.json'
def jsonToXml():
with open(filePath,'r',encoding='utf-8') as f:
jsonStr = f.read()
jsonStrToDict = json.loads(jsonStr)
xmlStr = xmltodict.unparse(jsonStrToDict,pretty=True)
print(xmlStr)
if __name__ == '__main__':
jsonToXml()
json文件内容如下:
{
"CityList": {
"city": [
{
"@provinceId": "280",
"@provinceName": "四川",
"@city": "513200",
"@Cityname": "阿坝藏族羌族自治州",
"@FirstLetter": "A"
},
{
"@provinceId": "991",
"@provinceName": "新疆",
"@city": "652900",
"@Cityname": "阿克苏地区",
"@FirstLetter": "A"
},
{
"@provinceId": "991",
"@provinceName": "新疆",
"@city": "659002",
"@Cityname": "阿拉尔",
"@FirstLetter": "A"
},
{
"@provinceId": "471",
"@provinceName": "内蒙古",
"@city": "152900",
"@Cityname": "阿拉善盟",
"@FirstLetter": "A"
},
{
"@provinceId": "991",
"@provinceName": "新疆",
"@city": "654300",
"@Cityname": "阿勒泰地区",
"@FirstLetter": "A"
},
{
"@provinceId": "891",
"@provinceName": "西藏",
"@city": "542500",
"@Cityname": "阿里地区",
"@FirstLetter": "A"
},
{
"@provinceId": "290",
"@provinceName": "陕西",
"@city": "610900",
"@Cityname": "安康",
"@FirstLetter": "A"
},
{
"@provinceId": "551",
"@provinceName": "安徽",
"@city": "340800",
"@Cityname": "安庆",
"@FirstLetter": "A"
},
{
"@provinceId": "851",
"@provinceName": "贵州",
"@city": "520400",
"@Cityname": "安顺",
"@FirstLetter": "A"
},
{
"@provinceId": "371",
"@provinceName": "河南",
"@city": "410500",
"@Cityname": "安阳",
"@FirstLetter": "A"
},
{
"@provinceId": "240",
"@provinceName": "辽宁",
"@city": "210300",
"@Cityname": "鞍山",
"@FirstLetter": "A"
}
]
}
}
执行脚本,转为XML格式: