# import xml.etree.cElementTree as ET #用ET 代指xml.etree.cElementTree模块,方便后面模块的取用
#
# tree = ET.parse('country')
# root = tree.getroot() #得到根节点
# print(root.tag) #得到标签名,,,root.tag意思是得到根的标签名
# for i in root:
# print(i.tag)
# for x in i:
# print(x.tag)
# print(i.attrib) #获取标签的属性值
# print(x.attrib)
# print(x.text) #获取标签的值
#xml文件的遍历
# for i in root:
# print(i.tag,i.attrib)
# for x in i:
# print(x.tag,x.text)
#只遍历year的值
# for i in root.iter('year'):
# print(i.tag,i.text)
#-----------------以上是查看-----------------
#---------------下面是修改xml文件-----------------------
import xml.etree.cElementTree as ET
tree = ET.parse('country')
root = tree.getroot()
#修改文件
# for node in root.iter('year'):
# new_node = int(node.text)+1
# node.text = str(new_node)
# node.set("updated","yes") #更新到xml文件中
# tree.write('abc.xml') #将内存中产生的数据写到一个新的文件里面,也可以直接覆盖原文件
# tree.write('conutry.xml')
#删除
#删除rank值大于50的国家
for i in root.findall('country'):
a = int(i.find('rank').text)
if a > 50:
root.remove(i)
tree.write('abc')
# ---------------
#自己创建一个xml文件
import xml.etree.ElementTree as ET
new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
age = ET.SubElement(name, "age", attrib={"checked": "no"})
sex = ET.SubElement(name, "sex")
sex.text = '33'
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
age.text = '19'
et = ET.ElementTree(new_xml) # 生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True)
ET.dump(new_xml) # 打印生成的格式