當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python XML轉Dictionary用法及代碼示例

在本文中,我們將討論如何使用 Python 將 XML 轉換為字典。

使用的模塊

  • xmltodict:它是一個 Python 模塊,讓您在使用 XML 時感覺就像在使用 [JSON]。在終端中運行以下命令來安裝模塊。

用法:

pip install xmltodict

  • 打印pprint 模塊以 well-formatted 和更具可讀性的方式提供了對 “pretty-print” 任意 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) 以 well-formatted 和可讀的方式打印字典。

用法:

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

例:將 XML 轉換為字典

使用的文件:

Python3


# 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)

輸出:

範例2:將 XML 轉換為字典

使用的文件:

Python3


# 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)

輸出:


相關用法


注:本文由純淨天空篩選整理自anilabhadatta大神的英文原創作品 Python program to convert XML to Dictionary。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。