0
点赞
收藏
分享

微信扫一扫

小白学 Python:将 XML 转换为字典的 Python 程序

在本文中,我们将讨论如何使用 Python 将 XML 转换为字典。

小白学 Python:将 XML 转换为字典的 Python 程序_xml

使用的模块

  • xmltodict:它是一个 Python 模块,使使用 XML 感觉就像使用 [JSON] 一样。在终端中运行以下命令来安装模块。

句法:

pip 安装 xmltodict

  • pprint: pprint 模块提供了以格式良好且更具可读性的方式“漂亮打印”任意 Python 数据结构的功能。

方法

  • 将必要的模块导入工作空间。
  • 以只读模式打开 XML 文件并使用 file.read() 读取内容并将其存储在变量中。

语法:

with open('filename', 'r', encoding='utf-8') as file:
    my_xml = file.read()

  • 使用xmltodict.parse()解析变量的内容并将其转换为字典。

语法 : 

xmltodict.parse(xml_input, encoding=’utf-8′, expat=expat, process_namespaces=False, namespace_separator=’:’, **kwargs)

  • 使用pprint(pretty print)以格式良好且可读的方式打印字典。

语法:

pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)

示例:将 XML 转换为字典

使用的文件:

小白学 Python:将 XML 转换为字典的 Python 程序_xml_02

Python:

# Import the required modules 
import xmltodict 
import pprint 

# Open the file and read the contents 
with open('example.xml', 'r', encoding='utf-8') as file: 
	my_xml = file.read() 

# Use xmltodict to parse and convert 
# the XML document 
my_dict = xmltodict.parse(my_xml) 

# Print the dictionary 
pprint.pprint(my_dict, indent=2) 

输出:

小白学 Python:将 XML 转换为字典的 Python 程序_Python_03

示例 2:将 XML 转换为字典

使用的文件:

小白学 Python:将 XML 转换为字典的 Python 程序_XML_04

Python:

# Import the required modules 
import xmltodict 
import pprint 

# Open the file and read the contents 
with open('example_2.xml', 'r', encoding='utf-8') as file: 
	my_xml = file.read() 

# Use xmltodict to parse and convert the 
# XML document 
my_dict = xmltodict.parse(my_xml) 

# Print the dictionary 
pprint.pprint(my_dict, indent=2) 

输出:

小白学 Python:将 XML 转换为字典的 Python 程序_xml_05

举报

相关推荐

0 条评论