chinajz 发表于 2022-12-28 20:16:21

python建立XML文件

本帖最后由 chinajz 于 2022-12-29 08:42 编辑

用tree.write()建立一个data.xml并写入以下内容:
<?xml version='1.0' encoding='utf-8'?>
<root>
<data1 word1="data11" word2="data22">data1text</data1>
<name1 word1="name11" word2="name22">name1text</name1>
</root>
代码:

    import xml.etree.ElementTree as ET   
    root = ET.Element("root")
    data1 = ET.Element("data1")
    root.append(data1)
    data1.set("word1", "data11")
    data1.set("word2", "data22")
    data1.text="data1text"
    name1 = ET.Element("name1")
    root.append(name1)
    name1.set("word1", "name11")
    name1.set("word2", "name22")
    name1.text = "name1text"
    tree = ET.ElementTree(root)
    tree.write("data.xml",encoding="utf-8", xml_declaration=True)
读取并显示:
data1.text=data1text
word1=data11
word2=data22
name1.text=name1text
word1=name11
word2=name22
页: [1]
查看完整版本: python建立XML文件