Python: Converting an XML format file into a JSON-formatted file

Source: Internet
Author: User
Tags python script

Since JSON-formatted files are highly convenient to work with and produce a large number of XML-formatted files every day, there is a need to convert XML-formatted files into JSON-formatted files.
Directly below the code, there are two versions, according to the requirements of the free choice:

#!/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();

The difference between the two versions is obvious, the first lacks flexibility, the second uses a similar position variable in the shell to make the Python script more flexible.

Ps:python study, we have what better way to achieve, welcome message discussion Oh ~

Python: Converting an XML format file into a JSON-formatted file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.