本文主要Python中,将xml格式数据转换成json格式数据的方法,以及相关的示例代码。

1、使用xmltodict和json实现

相关文档xmltodict 

import xmltodict, json
o = xmltodict.parse("""
<catalog>
    <maxid>4</maxid>
    <login username="pytest" passwd='123456'>
        <caption>Python</caption>
        <item id="4">
            <caption>测试</caption>
        </item>
    </login>
    <item id="2">
        <caption>Zope</caption>
    </item>
</catalog>
 """)
json.dumps(o) # '{"catalog": {"maxid": "4", "login": {"@username": "pytest", "@passwd": "123456", "caption": "Python", "item": {"@id": "4", "caption": "\\u6d4b\\u8bd5"}}, "item": {"@id": "2", "caption": "Zope"}}}'

或者

import xmltodict
data = requests.get(url)
xpars = xmltodict.parse(data.text)
json = json.dumps(xpars)
print json 

2、使用xmljson实现

import json, xmljson
from lxml.etree import fromstring, tostring
xml = fromstring("""
<catalog>
    <maxid>4</maxid>
    <login username="pytest" passwd='123456'>
        <caption>Python</caption>
        <item id="4">
            <caption>测试</caption>
        </item>
    </login>
    <item id="2">
        <caption>Zope</caption>
    </item>
</catalog>
 """)
json.dumps(xmljson.badgerfish.data(xml))

3、使用xml.etree实现

from xml.etree import ElementTree as ET
xml    = ET.parse('FILE_NAME.xml')
parsed = parseXmlToJson(xml)

def parseXmlToJson(xml):
  response = {}
  for child in list(xml):
    if len(list(child)) > 0:
      response[child.tag] = parseXmlToJson(child)
    else:
      response[child.tag] = child.text or ''
  return response

推荐文档