使用lxml库创建XML文档的步骤如下:
from lxml import etree
root = etree.Element("root")
child1 = etree.SubElement(root, "child1")
child2 = etree.SubElement(root, "child2")
child1.set("attribute", "value")
tree = etree.ElementTree(root)
tree.write("output.xml", encoding="UTF-8", xml_declaration=True)
完整的代码示例如下:
from lxml import etree
# 创建根节点
root = etree.Element("root")
# 创建子节点并添加到根节点中
child1 = etree.SubElement(root, "child1")
child2 = etree.SubElement(root, "child2")
# 添加子节点的属性
child1.set("attribute", "value")
# 创建XML文档对象,并将根节点添加到文档中
tree = etree.ElementTree(root)
# 将XML文档保存到文件中
tree.write("output.xml", encoding="UTF-8", xml_declaration=True)
运行以上代码后,会在当前目录下生成一个名为output.xml的XML文档,内容如下:
<?xml version='1.0' encoding='UTF-8'?>
<root>
<child1 attribute="value"/>
<child2/>
</root>