使用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>