如何用Python将XML文件转换为JSON?
我有一个XML文件,我想用Python把它转换成JSON文件,但我遇到了一些问题。
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
我正在使用ElementTree来解析这个XML文件,然后把它交给Simplejson进行序列化,像这样:
from xml.etree import ElementTree as ET
import simplejson
tree = ET.parse(Xml_file_path)
simplejson.dumps(tree)
但是我遇到了一个错误:TypeError: xml.etree.ElementTree.ElementTree对象在0x00C49DD0的位置不能被转换成JSON格式。
4 个回答
2
你可以试试用 xmljson 这个工具。相关的代码如下:
from xmljson import badgerfish as bf
from xml.etree.ElementTree import fromstring
s = '''<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>'''
json.dumps(bf.data(fromstring(s)))
8
这可能正是你想要的内容:
https://github.com/mutaku/xml2json
import xml2json
s = '''<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>'''
print xml2json.xml2json(s)