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 ElementTree
import json
LISTTYPE = 1
DICTTYPE = 0
def 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 LISTTYPE
def 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 report
if __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)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python如何從txt文件中提取特定數(shù)據(jù)
這篇文章主要給大家介紹了關(guān)于Python如何從txt文件中提取特定數(shù)據(jù)的相關(guān)資料,有時(shí)我們會(huì)遇到需要按行讀取文本的情況,我們要讀取txt文件獲得數(shù)據(jù),需要的朋友可以參考下2023-08-08
20行Python代碼實(shí)現(xiàn)一款永久免費(fèi)PDF編輯工具
本文主要介紹了Python代碼實(shí)現(xiàn)一款永久免費(fèi)PDF編輯工具,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
Python結(jié)合百度語(yǔ)音識(shí)別實(shí)現(xiàn)實(shí)時(shí)翻譯軟件的實(shí)現(xiàn)
這篇文章主要介紹了Python結(jié)合百度語(yǔ)音識(shí)別實(shí)現(xiàn)實(shí)時(shí)翻譯軟件的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
python爬蟲(chóng)爬取監(jiān)控教務(wù)系統(tǒng)的思路詳解
這篇文章主要介紹了python爬蟲(chóng)監(jiān)控教務(wù)系統(tǒng),主要實(shí)現(xiàn)思路是對(duì)已有的成績(jī)進(jìn)行處理,變?yōu)閘ist集合,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2020-01-01
python機(jī)器學(xué)習(xí)實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)示例解析
這篇文章主要為大家介紹了python機(jī)器學(xué)習(xí)python實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)的示例解析,在同樣在進(jìn)行python機(jī)器學(xué)習(xí)的同學(xué)可以借鑒參考下,希望能夠有所幫助2021-10-10
python運(yùn)行cmd命令10種方式并獲得返回值的高級(jí)技巧
這篇文章主要給大家介紹了關(guān)于python運(yùn)行cmd命令10種方式并獲得返回值的高級(jí)技巧,主要包括python腳本執(zhí)行CMD命令并返回結(jié)果的例子使用實(shí)例、應(yīng)用技巧,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-03-03
python利用tkinter實(shí)現(xiàn)屏保
這篇文章主要為大家詳細(xì)介紹了python利用tkinter實(shí)現(xiàn)屏保,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07
使用python加密主機(jī)文件幾種方法實(shí)現(xiàn)
本文主要介紹了使用python加密主機(jī)文件幾種方法實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02

