XML模块示例代码

# import xml.etree.ElementTree as et
# xml_tree=et.parse("xml1.xml")
# root=xml_tree.getroot()
# print(root.tag)
# 只遍历XML的文档
# for chid in root:
#     print(chid.tag,chid.attrib)
#     for sun in chid:
#         print(sun.tag,sun.text)
# 只遍历year的节点
# for node in root.iter("year"):
#     print(node.tag,node.text)


# import xml.etree.ElementTree as et
# # # 修改year节点
# et_tree=et.parse("xml1.xml")
# root=et_tree.getroot()
#
# for node in root.iter("year"):
#     print(node.tag,node.text)
#     new_year=int(node.text)+1
#     node.text=str(new_year)
#     # node.set("update2","yes")
# et_tree.write("xml2.xml")

#删除节点
# import xml.etree.ElementTree as et
# tree=et.parse("xml2.xml")
# root=tree.getroot()
# print(root.tag)
# for guojia in root.findall("country"):
#     rank1=int(guojia.find("rank").text)
#     print(rank1)
#     if rank1>50:
#         root.remove(guojia)
#
# tree.write("xml3.xml")

#创建XML
import xml.etree.cElementTree as et

xml4 = et.Element("name_list")
name=et.SubElement(xml4,"name",attrib={"enrolled":"yes"})
age=et.SubElement(name,"age",attrib={"chked":"no"})
age.text="20"
sex=et.SubElement(name,"sex")
sex.text="man"
name2=et.SubElement(xml4,"name2",attrib={"enrolled":"no"})
age=et.SubElement(name2,"age",)
age.text="20"
ET=et.ElementTree(xml4) #生成XML文档
ET.write("xml4.xml",encoding="utf-8",xml_declaration=True)#写入xml4的xml文件

et.dump(xml4)  #打印xml文档

 

posted @ 2021-03-09 11:57  菜鸟阿呆  阅读(572)  评论(0编辑  收藏  举报