一、
Python实现XML转JSON文件
本教程将介绍如何使用Python将XML文件转换为JSON格式的文件。
环境准备
首先你需要安装python 2.7或以上版本和pip。之后你可以使用以下命令安装所需模块:
pip install xmltodict
pip install json
实现过程
-
导入所需模块
python
import xmltodict
import json -
加载XML数据
python
with open('sample.xml') as xml_file:
data_dict = xmltodict.parse(xml_file.read())
xml_file.close()这将把XML数据转换成一个Python字典。
-
将字典转换成JSON
python
json_data = json.dumps(data_dict, indent=4)这将把Python字典转换成JSON格式的字符串,并使用4个空格缩进。
-
写入JSON文件
python
with open('sample.json', 'w') as json_file:
json_file.write(json_data)
json_file.close()这将把JSON数据写入文件中。
至此,完成了将XML文件转换为JSON文件的整个过程。
二、
XML转JSON示例
以下是一个XML示例,本教程将演示如何将其转换为JSON格式。
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
使用上述代码,我们可以得到以下JSON文件:
{
"catalog": {
"book": [
{
"@id": "bk101",
"author": "Gambardella, Matthew",
"title": "XML Developer's Guide",
"price": "44.95",
"publish_date": "2000-10-01",
"description": "An in-depth look at creating applications \n with XML."
},
{
"@id": "bk102",
"author": "Ralls, Kim",
"title": "Midnight Rain",
"price": "5.95",
"publish_date": "2000-12-16",
"description": "A former architect battles corporate zombies, \n an evil sorceress, and her own childhood to become queen \n of the world."
}
]
}
}
以上是将XML转换为JSON的示例,同样的方法可以应用于任何XML文件。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python实现xml转json文件的示例代码 - Python技术站