利用Python生成XML文件
发布时间:2024-01-08 08:12:36
在 Python 中可以使用内置的 xml.etree.ElementTree 模块来生成 XML 文件。以下是一个使用 Python 生成 XML 文件的例子:
import xml.etree.ElementTree as ET
# 创建根元素
root = ET.Element('catalog')
# 创建子元素
book1 = ET.SubElement(root, 'book')
book2 = ET.SubElement(root, 'book')
# 为子元素添加属性
book1.set('id', '1')
book2.set('id', '2')
# 创建子元素的子元素
title1 = ET.SubElement(book1, 'title')
title2 = ET.SubElement(book2, 'title')
author1 = ET.SubElement(book1, 'author')
author2 = ET.SubElement(book2, 'author')
# 设置子元素的文本内容
title1.text = 'Book 1'
title2.text = 'Book 2'
author1.text = 'Author 1'
author2.text = 'Author 2'
# 创建 XML 树对象
tree = ET.ElementTree(root)
# 保存 XML 文件
tree.write('catalog.xml', encoding='UTF-8', xml_declaration=True)
上述代码将生成一个名为 catalog.xml 的 XML 文件,其内容如下:
<?xml version='1.0' encoding='UTF-8'?>
<catalog>
<book id="1">
<title>Book 1</title>
<author>Author 1</author>
</book>
<book id="2">
<title>Book 2</title>
<author>Author 2</author>
</book>
</catalog>
上述代码中,我们首先导入了 xml.etree.ElementTree 模块。然后,我们创建了根元素 catalog,并为其添加了两个子元素 book。接着,我们为每个子元素添加了一个属性 id。然后,我们为每个子元素创建了子元素 title 和 author,并为其设置了文本内容。最后,我们使用 ElementTree 对象创建了 XML 树对象,并使用 write() 方法将 XML 内容保存到文件。
使用 Python 生成 XML 文件非常简单直观,你可以根据需要添加更多的元素和属性,构建出复杂的 XML 结构。
