使用xml.etree.ElementTree创建XML的核心步骤包括:导入模块、创建根元素、添加子元素与属性、设置文本内容、生成ElementTree对象并写入文件;注意事项有:使用ET.indent()提升可读性、指定encoding="utf-8"和xml_declaration=True保证编码规范、通过try-except处理文件写入异常;此外,lxml库功能更强,支持XPath和XSD验证,适合复杂场景。

在Python中创建XML文档,最常用且内置的方法是利用
xml.etree.ElementTree
lxml
使用
xml.etree.ElementTree
让我们以创建一个简单的“书籍列表”XML文档为例:
import xml.etree.ElementTree as ET
def create_book_list_xml():
# 1. 创建根元素
# 比如,我们想要一个名为 <bookstore> 的根元素
root = ET.Element(&quot;bookstore&quot;)
# 2. 添加第一个 <book> 元素
book1 = ET.SubElement(root, &quot;book&quot;, category=&quot;fiction&quot;) # category 是属性
title1 = ET.SubElement(book1, &quot;title&quot;)
title1.text = &quot;The Great Python Adventure&quot;
author1 = ET.SubElement(book1, &quot;author&quot;)
author1.text = &quot;Jane Doe&quot;
year1 = ET.SubElement(book1, &quot;year&quot;)
year1.text = &quot;2023&quot;
price1 = ET.SubElement(book1, &quot;price&quot;)
price1.text = &quot;29.99&quot;
# 3. 添加第二个 <book> 元素
book2 = ET.SubElement(root, &quot;book&quot;, category=&quot;programming&quot;)
title2 = ET.SubElement(book2, &quot;title&quot;)
title2.text = &quot;Mastering XML with Python&quot;
author2 = ET.SubElement(book2, &quot;author&quot;)
author2.text = &quot;John Smith&quot;
year2 = ET.SubElement(book2, &quot;year&quot;)
year2.text = &quot;2022&quot;
price2 = ET.SubElement(book2, &quot;price&quot;)
price2.text = &quot;39.50&quot;
# 4. 创建一个ElementTree对象
tree = ET.ElementTree(root)
# 5. 将XML树写入文件
# 我们可以通过 ET.indent() 来格式化输出,使其更具可读性
ET.indent(tree, space=&quot;\t&quot;, level=0) # 使用制表符进行缩进
try:
tree.write(&quot;bookstore.xml&quot;, encoding=&quot;utf-8&quot;, xml_declaration=True)
print(&quot;XML文档 'bookstore.xml' 已成功创建。&quot;)
except IOError as e:
print(f&quot;写入文件时发生错误: {e}&quot;)
# 调用函数来创建XML文件
if __name__ == &quot;__main__&quot;:
create_book_list_xml()运行这段代码后,你会在当前目录下得到一个名为
bookstore.xml
立即学习“Python免费学习笔记(深入)”;
<?xml version='1.0' encoding='utf-8'?>
<bookstore>
<book category=&quot;fiction&quot;>
<title>The Great Python Adventure</title>
<author>Jane Doe</author>
<year>2023</year>
<price>29.99</price>
</book>
<book category=&quot;programming&quot;>
<title>Mastering XML with Python</title>
<author>John Smith</author>
<year>2022</year>
<price>39.50</price>
</book>
</bookstore>xml.etree.ElementTree
当我们谈论用
ElementTree
首先,你需要一个最外层的“大盒子”,也就是根元素。这通过
ET.Element(&quot;根元素名&quot;)
然后,就是往这些盒子里装更小的盒子,或者直接放东西。添加子元素,我们用
ET.SubElement(父元素, &quot;子元素名&quot;, 属性字典)
<book category=&quot;fiction&quot;>
category
元素的文本内容,也就是标签之间的文字,比如
<title>Python</title>
Python
.text
.text
ElementTree
一个经常被忽略但又非常重要的点是编码。XML文件最终是要被机器或人阅读的,所以正确的编码至关重要。通常,我们都会选择
utf-8
tree.write()
encoding=&quot;utf-8&quot;
xml_declaration=True
<?xml version='1.0' encoding='utf-8'?>
至于可读性,原始的
ElementTree
ET.indent(tree)
ET.indent()
最后,别忘了错误处理。文件操作总是有可能失败的,比如磁盘空间不足、权限问题等等。用
try...except IOError
tree.write()
ElementTree
当然,
ElementTree
一个值得一提的是
xml.dom.minidom
minidom
ElementTree
minidom
另一个重量级选手是lxml
pip install lxml
ElementTree
lxml
ElementTree
minidom
ElementTree
lxml
ElementTree
lxml
简单来说:
xml.etree.ElementTree
xml.dom.minidom
lxml
生成复杂XML结构,特别是那些需要与外部系统交互的XML,确保其有效性和可读性是至关重要的。这不仅仅是编码规范的问题,更是保证数据交换顺畅的关键。
关于有效性,最权威的验证方式是使用XML Schema (XSD) 或 DTD (Document Type Definition)。这些是定义XML文档结构、数据类型和约束的语言。一个XML文档只有在符合其声明的Schema或DTD时,才被称为“有效”的。Python标准库本身并没有内置的XSD验证器,但
lxml
lxml
除了Schema验证,确保良好格式 (Well-formedness) 也是基本要求。这意味着XML必须有且只有一个根元素,所有标签都必须正确关闭,属性值必须用引号包裹等等。幸运的是,
ElementTree
lxml
&
&
至于可读性,这主要关乎代码和生成出的XML文件本身。
ET.indent()
lxml
pretty_print=True
book_title
BookTitle
<book>
<author>
ET.Comment()
在我的实践中,我发现一个常见的挑战是,当需求变化时,XML结构也需要随之调整。如果一开始的代码结构混乱,那么修改起来会非常痛苦。所以,投入一些时间去设计清晰的XML结构和模块化的生成代码,这绝对是一项值得的投资。有时,为了满足特定的外部系统要求,我们甚至需要生成一些“不那么完美”的XML,比如某些元素顺序必须固定,或者某些空元素不能省略。这时候,对XML生成库的深入理解和灵活运用就显得尤为重要了。
以上就是如何在Python中创建XML文档?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号