import xml.etree.cElementTree as ET#cElementTree是c语言编写的效率大于python语言编写的ElmentTree
root =ET.Element("Name",attrib={"Country":"China"})#生成根节点
Li =ET.SubElement(root,"LiLei",attrib={"age":"18"})#根下的分支
Li.text ="I am LiLei,happy to make friends with you!"#分支的内容
Han =ET.SubElement(root,"HanMeiMei",attrib={"age":"19"})
Han.text ="I am HanMeiMei,love you!"
xml_root =ET.ElementTree(root)#生成树,拿到树的对象
xml_root.write("xml_3.xml",encoding="utf8",xml_declaration=True)#写入文件中"""
输出结果:生成一个“xml_3.xml”的文件:
<?xml version='1.0' encoding='utf8'?>
<Name Country="China">
<LiLei age="18">I am LiLei,happy to make friends with you!</LiLei>
<HanMeiMei age="19">I am HanMeiMei,love you!</HanMeiMei>
</Name>
"""
解文件
import xml.etree.cElementTree as ET
tree =ET.parse("xml_3.xml")#拿到树,可进行增删改查,遍历
root =tree.getroot()#得到根节点