xmltodict 模块将xml格式转成json格式

1.1 : xmltodict 模块将xml格式转成json格式

<?xml version="1.0"?>                    <!--#版本号-->
<data>                                    <!--#data是一个标签随便写,data中包含三组数据,每组数据都是country标签-->
    <country name="Liechtenstein">    <!--#name是给country标签取的名字-->
        <rank updated="yes">2</rank>    <!--#两个</rank>中的2是数据排名,updated="yes"是属性可随便写-->
        <year>2008</year>                <!--#在2008年-->
        <gdppc>141100</gdppc>            <!--#人均gdp是141100-->
        <neighbor name="Austria" direction="E"/>          <!--#他有个邻居有两个属性 name 和 direction-->
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
xmltest.xml 原数据
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import xmltodict, json

with open('xmltest.xml','r') as f:
    str_xml = str(f.read())

str_xml = str_xml.replace('&','&#38;')  # xml格式不能有"&"符号
doc = xmltodict.parse(str_xml)
print json.dumps(doc)
xml_to_json.py
{
    "data": {
        "country": [{
            "@name": "Liechtenstein",
            "rank": {
                "@updated": "yes",
                "#text": "2"
            },
            "year": "2008",
            "gdppc": "141100",
            "neighbor": [{
                "@name": "Austria",
                "@direction": "E"
            }, {
                "@name": "Switzerland",
                "@direction": "W"
            }]
        }, {
            "@name": "Singapore",
            "rank": {
                "@updated": "yes",
                "#text": "5"
            },
            "year": "2011",
            "gdppc": "59900",
            "neighbor": {
                "@name": "Malaysia",
                "@direction": "N"
            }
        }, {
            "@name": "Panama",
            "rank": {
                "@updated": "yes",
                "#text": "69"
            },
            "year": "2011",
            "gdppc": "13600",
            "neighbor": [{
                "@name": "Costa Rica",
                "@direction": "W"
            }, {
                "@name": "Colombia",
                "@direction": "E"
            }]
        }]
    }
}
解析后的json文件
原文地址:https://www.cnblogs.com/jiaxinzhu/p/12596105.html