python3 xml文件转json,并且把xml key的首字母变成小写

python3 xml文件转json,并且把xml key的首字母变成小写

import xmltodict
import json
import re

with open('source.xml', 'r', encoding='UTF-8') as f:
    str_xml = f.read()

str_xml = str_xml.replace('&', '&')  # xml格式不能有"&"符号
json_string = json.dumps(xmltodict.parse(str_xml))
json_string = json_string.encode('utf-8').decode("unicode_escape")
#  "[A-Z]  替换 成 \L$0
# 将匹配的数字母变成小写
def lowstr(matched):
    value = matched.group('value')
    return value.lower()
json_string = re.sub('(?P<value>"[A-Z])',lowstr,json_string)
print(json_string)
with open('target.xml.json', 'w',encoding='UTF-8') as f:
    f.write(json_string)

 

posted @ 2022-02-19 09:27  testway  阅读(135)  评论(0编辑  收藏  举报