Python does not implement XML-to-JSON with third-party packages

Source: Internet
Author: User

XML to JSON? Is it hard to hear the pain, are the format of structured data necessary for this conversion? Yes, actually I also feel bored, but hands itch, always want to try. Online can also find a conversion tool called xmltodict, also very useful. My method is as follows, the principle is very simple, the code is also very short.

XML file: Testxml.xml

<?xml version= "1.0" encoding= "Utf-8"?><root> <person age= "Up" >    <name> Zhang San </name>    <sex> men </sex> </person> <person age= "des=" "Hello" >    <name> John Doe </name>    <sex> Women </sex> </person></root>

Python code:

From Xml.etree import ElementTree as Et;import json# reads the node from the XML file into JSON format and saves it to the file print (' Read node from xmlfile, transfer th EM to JSON, and save into Jsonfile: ') root=et.parse ("Testxml.xml"), F=open (' Testjson.json ', ' a ', encoding= "UTF8"); Each in root.getiterator (' person '):    tempdict=each.attrib for    Childnode in Each.getchildren ():        tempdict[ Childnode.tag]=childnode.text    tempjson=json.dumps (tempdict,ensure_ascii=false)    print (TempJson)    F.write (tempjson+ "\ n"), F.close () #从json文件中读取 and prints print (' Read JSON from Jsonfile: ') for Eachjson in open (' Testjson.json ' , ' R ', encoding= ' UTF8 '):    tempstr=json.loads (Eachjson);    Print (TEMPSTR)

The results are as follows:


Python does not implement XML-to-JSON with third-party packages

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.