Python生成带有嵌套结构的XML文件
发布时间:2023-12-11 17:38:32
XML(可扩展标记语言)是一种文本格式,用于存储和交换数据。在Python中,我们可以使用内置的xml.etree.ElementTree模块来生成XML文件。
下面是一个例子,演示如何生成带有嵌套结构的XML文件:
import xml.etree.ElementTree as ET
# 创建根元素
root = ET.Element("books")
# 创建书籍元素
book1 = ET.SubElement(root, "book")
book2 = ET.SubElement(root, "book")
# 创建标题元素
title1 = ET.SubElement(book1, "title")
title1.text = "Book 1"
title2 = ET.SubElement(book2, "title")
title2.text = "Book 2"
# 创建作者元素
author1 = ET.SubElement(book1, "author")
author1.text = "Author 1"
author2 = ET.SubElement(book2, "author")
author2.text = "Author 2"
# 创建价格元素
price1 = ET.SubElement(book1, "price")
price1.text = "19.99"
price2 = ET.SubElement(book2, "price")
price2.text = "9.99"
# 创建XML树
tree = ET.ElementTree(root)
# 将XML树写入文件
tree.write("books.xml")
在上面的例子中,我们首先导入了xml.etree.ElementTree模块,然后创建一个根元素root,并使用ET.SubElement()方法创建了两个book子元素。
接下来,我们为每个book元素创建了title、author和price子元素,并使用.text属性设置了它们的文本内容。
最后,我们使用ET.ElementTree()方法创建了一个XML树,并使用.write()方法将它写入名为books.xml的文件中。
生成的books.xml文件如下所示:
<books>
<book>
<title>Book 1</title>
<author>Author 1</author>
<price>19.99</price>
</book>
<book>
<title>Book 2</title>
<author>Author 2</author>
<price>9.99</price>
</book>
</books>
上述例子演示了如何使用xml.etree.ElementTree模块生成带有嵌套结构的XML文件。你可以根据需要自定义元素和属性,并设置它们的值。这种方法非常灵活,适用于生成各种复杂的XML文件。
