python实现xml转json文件的示例代码
使用了Python的xml.etree.ElementTree库
xml.etree.ElementTree库简介
xml.etree.ElementTree模块实现了一个简单而高效的API用于解析和创建XML数据。xml.etree.ElementTree模块对于恶意构造的数据是不安全的。如果您需要解析不受信任或未经验证的数据,请参阅XML漏洞。
参考文献:https://docs.python.org/3.6/library/xml.etree.elementtree.html
fromxml.etreeimportElementTree importjson LISTTYPE=1 DICTTYPE=0 defgetDictResults(res_dicts,iters): result_dicts={} foriteriniters.getchildren(): iterxml(iter,result_dicts) ifresult_dicts: res_dicts[iters.tag].update(result_dicts) defgetListResults(res_dicts,iters): result_lists=[] foriteriniters.getchildren(): result_dicts={} iterxml(iter,result_dicts) result_lists.append(result_dicts.copy()) del(result_dicts) ifresult_lists: iflen(res_dicts[iters.tag].items())==0: res_dicts[iters.tag]=result_lists.copy() else: forresobjinresult_lists: resobjkey=list(resobj.keys())[0] ifres_dicts[iters.tag].get(resobjkey)==None: res_dicts[iters.tag].update(resobj) else: iftype(res_dicts[iters.tag][resobjkey])==list: res_dicts[iters.tag][resobjkey].append(resobj[resobjkey].copy()) else: old_value=res_dicts[iters.tag][resobjkey] res_dicts[iters.tag][resobjkey]=[] res_dicts[iters.tag][resobjkey].append(old_value) res_dicts[iters.tag][resobjkey].append(resobj[resobjkey].copy()) del(result_lists) defcheckxmlchildrentype(iters): taglist=[] foriteriniters.getchildren(): taglist.append(iter.tag) iflen(set(taglist))==len(taglist): returnDICTTYPE else: returnLISTTYPE defgetResults(res_dicts,iters): ifcheckxmlchildrentype(iters): returngetListResults(res_dicts,iters) else: returngetDictResults(res_dicts,iters) #@res_dicts{} defiterxml(iter,res_dicts): res_dicts[iter.tag]={} ifiter.attrib: fork,vindict(iter.attrib).items(): res_dicts[iter.tag].update({k:v}) ifiter.textisnotNoneanditer.text.strip()!="": res_dicts[iter.tag].update({"__XmlTagText__":iter.text.strip()}) ifiter.getchildren(): getResults(res_dicts,iter) defparserxmltojson(file_path): try: tree=ElementTree.parse(file_path) exceptExceptionase: #multi-byteencodingsarenotsupported把字符集改成utf-8就可以 #encodingspecifiedinXMLdeclarationisincorrectxmlencoding标识和文件的字符集不同 #syntaxerror语法错误,乱码等 #notwell-formed(invalidtoken)编辑器点击后字符集被修改成ASCII等,或者文件本身字符集和xmlencoding不相同 print("Parser{}Error,Errmsg:{}".format(file_path,e)) return"" iftreeisNone: print("{}isNone.".format(file_path)) return"" root=tree.getroot() report={} iterxml(root,report) #returngetDictResults(root) returnreport if__name__=="__main__": jsonret=parserxmltojson("test.xml") withopen("test.json","w",encoding="utf-8")asfd: fd.write(json.dumps(jsonret,ensure_ascii=False,indent=4)) print(json.dumps(jsonret,ensure_ascii=False,indent=4))
以上就是python实现xml转json文件的示例代码的详细内容,更多关于python实现xml转json文件的资料请关注毛票票其它相关文章!