使用lxml庫創(chuàng)建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
# 創(chuàng)建根節(jié)點(diǎn)
root = etree.Element("root")
# 創(chuàng)建子節(jié)點(diǎn)并添加到根節(jié)點(diǎn)中
child1 = etree.SubElement(root, "child1")
child2 = etree.SubElement(root, "child2")
# 添加子節(jié)點(diǎn)的屬性
child1.set("attribute", "value")
# 創(chuàng)建XML文檔對象,并將根節(jié)點(diǎn)添加到文檔中
tree = etree.ElementTree(root)
# 將XML文檔保存到文件中
tree.write("output.xml", encoding="UTF-8", xml_declaration=True)
運(yùn)行以上代碼后,會(huì)在當(dāng)前目錄下生成一個(gè)名為output.xml的XML文檔,內(nèi)容如下:
<?xml version='1.0' encoding='UTF-8'?>
<root>
<child1 attribute="value"/>
<child2/>
</root>