python:將xml格式檔案轉換成json格式檔案

來源:互聯網
上載者:User

標籤:Python   指令碼   xml轉json   

由於json格式的檔案在處理起來,有很強的便利性,而工作中每天產生大量的xml格式的檔案,所以有需求將xml格式的檔案轉換成json格式的檔案。
下面直接貼出代碼,有兩個版本,根據需求自由選擇:

#!/usr/bin/python# -*- coding: utf-8 -*-#Function:Xml_To_Json#version 1.0#Author: Herman#需要用到的兩個模組import xmltodict; import json;#定義函數def pythonXmlToJson():    with  open(‘filename.xml‘, ‘r‘) as f:        xmlStr = f.read()    convertedDict = xmltodict.parse(xmlStr);    jsonStr = json.dumps(convertedDict, indent=1);    print jsonStr;#執行函數if __name__=="__main__":    pythonXmlToJson();
#!/usr/bin/python# -*- coding: utf-8 -*-#Function:Xml_To_Json#version 1.1#Author: Herman#Date: 2018-06-01#Usage: python Xml_To_Json.py xmlfile_dir >> tar_dirimport xmltodict;import json;import sys;def pythonXmlToJson():    with  open(sys.argv[1], ‘r‘) as f:        xmlStr = f.read()    convertedDict = xmltodict.parse(xmlStr);    jsonStr = json.dumps(convertedDict, indent=1);    print jsonStr;if __name__=="__main__":    pythonXmlToJson();

這兩個版本的區別其實很明顯了,第一個缺乏靈活性,第二個使用了一個類似shell中位置變數,讓這個Python指令碼更有靈活性。

PS:Python學習中,大家有什麼更好的實現方式,歡迎留言討論哦~

python:將xml格式檔案轉換成json格式檔案

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.