欢迎访问宙启技术站
智能推送

Python中使用xmltodictunparse()函数将XML数据转换为可读性更高的格式

发布时间:2024-01-19 02:50:31

在Python中,可以使用xmltodict模块中的unparse()函数将XML数据转换为可读性更高的格式。unparse()函数将一个数据字典转换为XML格式,并返回一个字符串。

下面是一个使用xmltodict模块中的unparse()函数转换XML数据的示例代码:

import xmltodict

# 定义一个XML数据字典
data = {
    'bookstore': {
        'book': [
            {
                'category': 'cooking',
                'title': 'Italian Food',
                'author': 'John Smith',
                'year': '2009',
                'price': '39.95'
            },
            {
                'category': 'programming',
                'title': 'Python 101',
                'author': 'Jane Doe',
                'year': '2014',
                'price': '29.99'
            },
            {
                'category': 'programming',
                'title': 'Java Basics',
                'author': 'John Doe',
                'year': '2017',
                'price': '45.50'
            }
        ]
    }
}

# 使用unparse()函数将数据转换为XML格式
xml_data = xmltodict.unparse(data, pretty=True)

# 打印转换后的XML数据
print(xml_data)

运行以上代码,将得到一个可读性更高的XML格式的输出:

<bookstore>
    <book>
        <category>cooking</category>
        <title>Italian Food</title>
        <author>John Smith</author>
        <year>2009</year>
        <price>39.95</price>
    </book>
    <book>
        <category>programming</category>
        <title>Python 101</title>
        <author>Jane Doe</author>
        <year>2014</year>
        <price>29.99</price>
    </book>
    <book>
        <category>programming</category>
        <title>Java Basics</title>
        <author>John Doe</author>
        <year>2017</year>
        <price>45.50</price>
    </book>
</bookstore>

在上面的示例中,我们首先定义了一个XML数据字典。然后,使用unparse()函数将数据转换为XML格式。我们还将pretty参数设置为True,以便生成可读性更高的XML格式。最后,打印转换后的XML数据。

需要注意的是,xmltodict模块是一个第三方模块,需要使用pip install xmltodict命令安装。