打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python3实现xml转json文件

使用了Python的 xml.etree.ElementTree 库,Python版本Python 3.6.6

from xml.etree import ElementTreeLISTTYPE = 1DICTTYPE = 0def getDictResults(res_dicts, iters):    result_dicts = {}    for iter in iters.getchildren():        iterxml(iter, result_dicts)    if result_dicts:        res_dicts[iters.tag].update(result_dicts)def getListResults(res_dicts, iters):    result_lists = []    for iter in iters.getchildren():        result_dicts = {}        iterxml(iter, result_dicts)        result_lists.append(result_dicts.copy())        del(result_dicts)        if result_lists:        if len(res_dicts[iters.tag].items()) == 0:            res_dicts[iters.tag] = result_lists.copy()        else:            res_dicts[iters.tag]["__XmlObjChildren__"] = result_lists.copy()        del(result_lists)def checkxmlchildrentype(iters):    taglist = []    for iter in iters.getchildren():        taglist.append(iter.tag)    if len(set(taglist)) == len(taglist):        return DICTTYPE    else:        return LISTTYPEdef getResults(res_dicts, iters):    if checkxmlchildrentype(iters):        return getListResults(res_dicts, iters)    else:        return getDictResults(res_dicts, iters)#@res_dicts    {}def iterxml(iter, res_dicts):    res_dicts[iter.tag] = {}    if iter.attrib:        for k,v in dict(iter.attrib).items():            res_dicts[iter.tag].update({k : v})        if iter.text is not None and iter.text.strip() != "":        res_dicts[iter.tag].update({"__XmlTagText__" : iter.text.strip()})        if iter.getchildren():        getResults(res_dicts, iter)def parserxmltojson(file_path):    try:        tree = ElementTree.parse(file_path)    except Exception as e:        #multi-byte encodings are not supported    把字符集改成utf-8就可以        #encoding specified in XML declaration is incorrect    xml encoding标识和文件的字符集不同        #syntax error    语法错误,乱码等        #not well-formed (invalid token)    编辑器点击后字符集被修改成ASCII等,或者文件本身字符集和xml encoding不相同        print("Parser {} Error, Errmsg: {}".format(file_path, e))        return ""    if tree is None:        print("{} is None.".format(file_path))        return ""    root = tree.getroot()    report = {}    iterxml(root, report)    #return getDictResults(root)    return reportif __name__ == "__main__":    jsonret = parserxmltojson("test.xml")    with open("test.json", "w", encoding="utf-8") as fd:        fd.write(str(jsonret))    print(jsonret)

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Pytest-接口请求实例(GET单参数和参数化请求)
Python 中的一些小技巧总结,新手必备知识点
用Python写个迷你出门问问|10几行代码搞定
面向 Java 开发人员的 Ajax(二): Ajax 的 Java 对象序列化
python 装饰器的使用
使用kubeadm安装Kubernetes v1.10 之 docker 私有镜像库搭建
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服