Python程式:將XML轉換為字典


可擴充套件標記語言(XML)是一種廣泛用於表示結構化資訊的格式。它是一種標記語言,允許我們定義自己的標籤來描述資料及其結構。

XML的設計既可供人類閱讀,也可供機器讀取。它使用起始標籤和結束標籤來包含元素,這些元素可以具有屬性幷包含巢狀元素。XML文件的結構由一組稱為文件型別定義(DTD)或XML模式的規則定義。

在本文中,我們將瞭解如何使用Python程式設計將XML轉換為字典。

輸入輸出場景

以下是XML到字典轉換的輸入輸出場景:

輸入XML

<root>
    <data>
      <fruit>
        <name>Strawberry</name>
        <color>Red</color>
        <price>2.49</price>
      </fruit>
      <vegetable>
        <name>Spinach</name>
        <color>Green</color>
        <price>1.99</price>
      </vegetable>
    </data>
</root>

輸出字典

{'root': {'data': {'fruit': {'name': 'Strawberry', 'color': 'Red', 'price': '2.49'}, 'vegetable': {'name': 'Spinach', 'color': 'Green', 'price': '1.99'}}}}

使用xmltodict庫

Python中的xmltodict庫提供了xmltodict.parse()函式來解析XML資料並將其轉換為Python字典。

要使用xmltodict庫進行XML到字典的轉換,我們需要先安裝它。它不是Python標準庫的一部分,但我們可以使用pip輕鬆安裝它。命令如下:

示例

#importing xmltodict module
import xmltodict

def xml_to_dict(xml_data):
    #converting xml to dictionary
    dict_data = xmltodict.parse(xml_data)
    return dict_data

#defining an xml string
xml_data = '''
<root>
    <data>
      <fruit>
        <name>Strawberry</name>
        <color>Red</color>
        <price>2.49</price>
      </fruit>
      <vegetable>
        <name>Spinach</name>
        <color>Green</color>
        <price>1.99</price>
      </vegetable>
    </data>
</root>
'''

result_dict = xml_to_dict(xml_data)
print('Output Dictionary:')
print(result_dict)

輸出

Output Dictionary:
{'root': {'data': {'fruit': {'name': 'Strawberry', 'color': 'Red', 'price': '2.49'}, 'vegetable': {'name': 'Spinach', 'color': 'Green', 'price': '1.99'}}}}

示例

在這個例子中,我們可以看到如何使用xmltodict模組將來自檔案的XML資料轉換為字典。

import xmltodict

def xml_file_to_dict(file_path):
    with open(file_path, 'r') as xml_file:
        xml_data = xml_file.read()
        dict_data = xmltodict.parse(xml_data)
        return dict_data

#defining an xml file path
file_path = 'Sample.xml'
result_dict = xml_file_to_dict(file_path)
print('Output Dictionary:')
print(result_dict)

輸出

Output Dictionary:
{'market': {'fruits': {'fruit': [{'name': 'Apple', 'color': 'Red', 'price': '1.99'}, {'name': 'Banana', 'color': 'Yellow', 'price': '0.99'}, {'name': 'Orange', 'color': 'Orange', 'price': '1.49'}]}, 'vegetables': {'vegetable': [{'name': 'Carrot', 'color': 'Orange', 'price': '0.79'}, {'name': 'Broccoli', 'color': 'Green', 'price': '1.29'}, {'name': 'Tomato', 'color': 'Red', 'price': '0.99'}]}}}

使用xml.etree.ElementTree模組

xml.etree.ElementTree.fromstring()函式是Python標準庫中xml.etree.ElementTree模組提供的一種方法。它用於解析字串格式的XML資料,並建立一個表示XML樹根的Element物件。以下是fromstring()函式的語法。此函式返回一個表示XML樹根的Element物件。

xml.etree.ElementTree.fromstring(xml_string)

其中,xml_string是一個包含要解析的XML資料的字串。

示例

在這個例子中,我們將使用xml.etree.ElementTree.fromstring()函式將XML轉換為字典。

import xml.etree.ElementTree as ET

def xml_to_dict(xml_data):
    root = ET.fromstring(xml_data)
    result = {}
    for child in root:
        if len(child) == 0:
            result[child.tag] = child.text
        else:
            result[child.tag] = xml_to_dict(ET.tostring(child))
    return result

#defining an xml string
xml_data = '''
<root>
    <data>
      <fruit>
        <name>Strawberry</name>
        <color>Red</color>
        <price>2.49</price>
      </fruit>
      <vegetable>
        <name>Spinach</name>
        <color>Green</color>
        <price>1.99</price>
      </vegetable>
    </data>
</root>
'''

result_dict = xml_to_dict(xml_data)
print('Output Dictionary:')
print(result_dict)

輸出

Output Dictionary:
{'data': {'fruit': {'name': 'Strawberry', 'color': 'Red', 'price': '2.49'}, 'vegetable': {'name': 'Spinach', 'color': 'Green', 'price': '1.99'}}}

這些是使用Python程式設計將XML轉換為字典的幾個示例。

更新於:2023年8月29日

3K+瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告