Python数据存储之XML文档和字典的互转

  • Post category:Python

下面我将详细讲解Python数据存储之XML文档和字典的互转的完整攻略。

什么是XML文档和字典

XML(Extensible Markup Language)是一种标记语言,用于描述和传输数据。XML文档是用标签定义数据的格式和内容,比如:

<book>
  <title>A Brief History of Time</title>
  <author>Stephen Hawking</author>
  <publisher>Bantam Dell Publishing Group</publisher>
  <price>19.95</price>
</book>

而字典(dictionary)是Python中的一种数据结构,用于存储键值对。Python字典的定义示例如下:

book = {
    'title': 'A Brief History of Time',
    'author': 'Stephen Hawking',
    'publisher': 'Bantam Dell Publishing Group',
    'price': 19.95
}

XML文档和字典的互转

将XML文档转换成Python字典,或将Python字典转换成XML文档,可以用Python内置的xml模块。

XML文档转换成Python字典

示例1:假设我们有一个books.xml的文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<books>
  <book id="1">
    <title>A Brief History of Time</title>
    <author>Stephen Hawking</author>
    <publisher>Bantam Dell Publishing Group</publisher>
    <price>19.95</price>
  </book>
  <book id="2">
    <title>1984</title>
    <author>George Orwell</author>
    <publisher>Secker and Warburg</publisher>
    <price>9.99</price>
  </book>
</books>

我们用Python读取这个XML文件,并将其转换成字典,示例代码如下:

import xml.etree.ElementTree as ET

tree = ET.parse('books.xml')
root = tree.getroot()

books = []
for book in root.findall('book'):
    book_dict = {}
    for child in book:
        book_dict[child.tag] = child.text
    book_dict['id'] = book.attrib['id']
    books.append(book_dict)

print(books)

输出结果如下:

[
    {
        'title': 'A Brief History of Time',
        'author': 'Stephen Hawking',
        'publisher': 'Bantam Dell Publishing Group',
        'price': '19.95',
        'id': '1'
    }, 
    {
        'title': '1984',
        'author': 'George Orwell',
        'publisher': 'Secker and Warburg',
        'price': '9.99',
        'id': '2'
    }
]

示例2:假设我们有一个简单的XML文档,内容如下:

<data>
    <name>John</name>
    <age>28</age>
    <gender>male</gender>
</data>

我们用Python读取这个XML文档,并将其转换成字典,示例代码如下:

import xml.etree.ElementTree as ET

tree = ET.parse('data.xml')
root = tree.getroot()

data_dict = {}
for child in root:
    data_dict[child.tag] = child.text

print(data_dict)

输出结果如下:

{
    'name': 'John',
    'age': '28',
    'gender': 'male'
}

Python字典转换成XML文档

示例1:假设我们有一个包含多个字典的列表,示例代码如下:

books = [
    {
        'title': 'A Brief History of Time',
        'author': 'Stephen Hawking',
        'publisher': 'Bantam Dell Publishing Group',
        'price': '19.95',
        'id': '1'
    }, 
    {
        'title': '1984',
        'author': 'George Orwell',
        'publisher': 'Secker and Warburg',
        'price': '9.99',
        'id': '2'
    }
]

我们将这个字典列表转换成XML文档,并保存成books.xml文件,示例代码如下:

import xml.etree.ElementTree as ET

root = ET.Element('books')

for book in books:
    node_book = ET.Element('book', id=book['id'])
    node_title = ET.SubElement(node_book, 'title')
    node_title.text = book['title']
    node_author = ET.SubElement(node_book, 'author')
    node_author.text = book['author']
    node_publisher = ET.SubElement(node_book, 'publisher')
    node_publisher.text = book['publisher']
    node_price = ET.SubElement(node_book, 'price')
    node_price.text = book['price']
    root.append(node_book)

tree = ET.ElementTree(root)
tree.write('books.xml', encoding='UTF-8')

生成的books.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<books>
  <book id="1">
    <title>A Brief History of Time</title>
    <author>Stephen Hawking</author>
    <publisher>Bantam Dell Publishing Group</publisher>
    <price>19.95</price>
  </book>
  <book id="2">
    <title>1984</title>
    <author>George Orwell</author>
    <publisher>Secker and Warburg</publisher>
    <price>9.99</price>
  </book>
</books>

示例2:假设我们有一个包含个人信息的字典,示例代码如下:

person = {
    'name': 'John',
    'age': '28',
    'gender': 'male'
}

我们将这个字典转换成XML文档,并保存成data.xml文件,示例代码如下:

import xml.etree.ElementTree as ET

root = ET.Element('data')

for key, value in person.items():
    node = ET.Element(key)
    node.text = value
    root.append(node)

tree = ET.ElementTree(root)
tree.write('data.xml', encoding='UTF-8')

生成的data.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<data>
  <name>John</name>
  <age>28</age>
  <gender>male</gender>
</data>

以上就是Python数据存储之XML文档和字典的互转的完整攻略,希望对你有帮助。