python實(shí)現(xiàn)xml轉(zhuǎn)json文件的示例代碼
使用了Python的 xml.etree.ElementTree 庫(kù)
xml.etree.ElementTree 庫(kù)簡(jiǎn)介xml.etree.ElementTree模塊實(shí)現(xiàn)了一個(gè)簡(jiǎn)單而高效的API用于解析和創(chuàng)建XML數(shù)據(jù)。xml.etree.ElementTree模塊對(duì)于惡意構(gòu)造的數(shù)據(jù)是不安全的。如果您需要解析不受信任或未經(jīng)驗(yàn)證的數(shù)據(jù),請(qǐng)參閱XML漏洞。參考文獻(xiàn):https://docs.python.org/3.6/library/xml.etree.elementtree.html
from xml.etree import ElementTreeimport jsonLISTTYPE = 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: for resobj in result_lists:resobjkey = list(resobj.keys())[0]if res_dicts[iters.tag].get(resobjkey) == None: res_dicts[iters.tag].update(resobj)else: if type(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)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標(biāo)識(shí)和文件的字符集不同 #syntax error 語(yǔ)法錯(cuò)誤,亂碼等 #not well-formed (invalid token) 編輯器點(diǎn)擊后字符集被修改成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(json.dumps(jsonret, ensure_ascii=False, indent=4)) print(json.dumps(jsonret, ensure_ascii=False, indent=4))
以上就是python實(shí)現(xiàn)xml轉(zhuǎn)json文件的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于python實(shí)現(xiàn)xml轉(zhuǎn)json文件的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Android table布局開(kāi)發(fā)實(shí)現(xiàn)簡(jiǎn)單計(jì)算器2. 理解PHP5中static和const關(guān)鍵字3. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼4. php模擬實(shí)現(xiàn)斗地主發(fā)牌5. IntelliJ IDEA安裝插件的方法步驟6. phpstorm恢復(fù)默認(rèn)設(shè)置的方法步驟7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Python random庫(kù)使用方法及異常處理方案9. Vuex localStorage的具體使用10. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟

網(wǎng)公網(wǎng)安備