本文目录导读:

Python 中生成 XML 文件有多种方法,这里介绍 3 种最常用的方案:
使用 ElementTree(推荐,标准库)
import xml.etree.ElementTree as ET
# 创建根元素
root = ET.Element("bookstore")
# 创建子元素
book = ET.SubElement(root, "book")
book.set("category", "Python")
# 添加子元素= ET.SubElement(book, "title")text = "Python编程入门"set("lang", "zh")
author = ET.SubElement(book, "author")
author.text = "张三"
price = ET.SubElement(book, "price")
price.text = "59.9"
# 添加第二本书
book2 = ET.SubElement(root, "book")
book2.set("category", "开发")
ET.SubElement(book2, "title").text = "机器学习实战"
ET.SubElement(book2, "author").text = "李四"
ET.SubElement(book2, "price").text = "79.9"
# 生成XML字符串
xml_str = ET.tostring(root, encoding='utf-8', method='xml')
print(xml_str.decode('utf-8'))
# 保存到文件
tree = ET.ElementTree(root)
tree.write("books.xml", encoding='utf-8', xml_declaration=True)
使用 lxml(功能更强大)
from lxml import etree
# 创建根元素
root = etree.Element("bookstore")
# 创建子元素
book = etree.SubElement(root, "book")
book.set("category", "Python")
# 添加子元素= etree.SubElement(book, "title")text = "Python编程入门"set("lang", "zh")
author = etree.SubElement(book, "author")
author.text = "张三"
price = etree.SubElement(book, "price")
price.text = "59.9"
# 生成漂亮的格式化XML
xml_str = etree.tostring(root, pretty_print=True, encoding='utf-8', xml_declaration=True)
print(xml_str.decode('utf-8'))
# 保存到文件
tree = etree.ElementTree(root)
tree.write("books_lxml.xml", encoding='utf-8', xml_declaration=True, pretty_print=True)
使用 dicttoxml(从字典生成)
from dicttoxml import dicttoxml
# 准备数据
data = {
"bookstore": {
"book": [
{
"@category": "Python",
"title": {"@lang": "zh", "#text": "Python编程入门"},
"author": "张三",
"price": "59.9"
},
{
"@category": "开发",
"title": "机器学习实战",
"author": "李四",
"price": "79.9"
}
]
}
}
# 转换为XML
xml_bytes = dicttoxml(data, custom_root='root', attr_type=False)
xml_str = xml_bytes.decode('utf-8')
print(xml_str)
# 保存到文件
with open('books_dict.xml', 'w', encoding='utf-8') as f:
f.write(xml_str)
完整示例:从列表数据生成
import xml.etree.ElementTree as ET
def create_xml_from_data(books_data, output_file="output.xml"):
"""从列表数据生成XML文件"""
root = ET.Element("bookstore")
for book_data in books_data:
book = ET.SubElement(root, "book")
book.set("category", book_data.get("category", ""))
# 添加基本信息
for key, value in book_data.items():
if key != "category": # 跳过category属性
element = ET.SubElement(book, key)
element.text = str(value)
# 保存文件
tree = ET.ElementTree(root)
tree.write(output_file, encoding='utf-8', xml_declaration=True)
print(f"XML文件已保存到: {output_file}")
# 示例数据
books = [
{"category": "Python", "title": "Python编程", "author": "张三", "price": 59.9},
{"category": "开发", "title": "机器学习", "author": "李四", "price": 79.9},
{"category": "教材", "title": "数据结构", "author": "王五", "price": 45.0}
]
# 生成XML
create_xml_from_data(books)
生成的美化XML示例:
<?xml version='1.0' encoding='utf-8'?>
<bookstore>
<book category="Python">
<title lang="zh">Python编程入门</title>
<author>张三</author>
<price>59.9</price>
</book>
<book category="开发">
<title>机器学习实战</title>
<author>李四</author>
<price>79.9</price>
</book>
</bookstore>
选择建议:
| 库 | 优点 | 适用场景 |
|---|---|---|
| ElementTree | 标准库,无需安装,轻量级 | 简单XML生成,基础需求 |
| lxml | 功能强大,支持XPath,美化输出 | 复杂XML,需要高级操作 |
| dicttoxml | 从字典快速生成 | 简单数据转XML |
推荐: 大多数情况使用 ElementTree 就足够了,它是 Python 标准库,功能完善,如果需要更丰富的功能(如XPath、Schema验证等),使用 lxml。