溫馨提示×

怎么使用lxml創(chuàng)建XML文檔

小億
102
2024-05-14 11:20:16
欄目: 編程語言

使用lxml庫創(chuàng)建XML文檔的步驟如下:

  1. 導(dǎo)入lxml庫:
from lxml import etree
  1. 創(chuàng)建根節(jié)點(diǎn):
root = etree.Element("root")
  1. 創(chuàng)建子節(jié)點(diǎn)并添加到根節(jié)點(diǎn)中:
child1 = etree.SubElement(root, "child1")
child2 = etree.SubElement(root, "child2")
  1. 添加子節(jié)點(diǎn)的屬性:
child1.set("attribute", "value")
  1. 創(chuàng)建XML文檔對象,并將根節(jié)點(diǎn)添加到文檔中:
tree = etree.ElementTree(root)
  1. 將XML文檔保存到文件中:
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>

0