在Python中如何创建一个XML文档?请使用xml模块给出示例代码。
import xml.etree.ElementTree as ET
# 创建根节点
root = ET.Element("Employees")
# 创建子节点,并添加属性
employee1 = ET.SubElement(root, "Employee", id="1")
name1 = ET.SubElement(employee1, "Name")
name1.text = "张三"
position1 = ET.SubElement(employee1, "Position")
position1.text = "软件工程师"
employee2 = ET.SubElement(root, "Employee", id="2")
name2 = ET.SubElement(employee2, "Name")
name2.text = "李四"
position2 = ET.SubElement(employee2, "Position")
position2.text = "数据分析师"
# 生成XML文档
xml_data = ET.tostring(root, encoding="unicode", method="xml")
print(xml_data)
详细说明
-
导入模块:首先需要导入
xml.etree.ElementTree模块,通常简称为ET。这个模块提供了创建和操作XML文档的功能。 -
创建根节点:使用
ET.Element()方法创建XML文档的根节点。根节点是所有子节点的容器。例如,创建一个名为Employees的根节点:root = ET.Element("Employees") -
添加子节点:使用
ET.SubElement()方法在根节点下添加子节点。子节点可以包含属性(通过关键字参数传递)和文本内容(通过.text属性设置)。例如,创建两个Employee子节点:employee1 = ET.SubElement(root, "Employee", id="1") -
设置节点内容:为子节点的子节点(如
Name和Position)设置文本内容:name1 = ET.SubElement(employee1, "Name") name1.text = "张三" -
生成XML字符串:通过
ET.tostring()方法将整个XML树转换为字符串。可以通过encoding和method参数指定编码和格式。例如:xml_data = ET.tostring(root, encoding="unicode", method="xml") -
输出结果:打印生成的XML字符串,结果如下:
<Employees> <Employee id="1"> <Name>张三</Name> <Position>软件工程师</Position> </Employee> <Employee id="2"> <Name>李四</Name> <Position>数据分析师</Position> </Employee> </Employees>
其他注意事项
- 修改XML文档:可以通过
ET.Element对象的方法(如append、remove)动态增删节点。 - 解析XML文档:使用
ET.parse()方法可以从文件加载XML文档,并使用find或findall方法查询节点。 - 美化输出:默认生成的XML字符串没有缩进,如果需要美化输出,可以手动调整或使用第三方库(如
lxml)。