python标准库常用模块(四)-----------------------------XML处理模块详解

再进行处理之前,要加入如下代码:

import xml.etree.ElementTree as ET#导入xml处理包

tree = ET.parse("xmltest.xml")#打开xml文件
root = tree.getroot()#获取这个文件的根
print(root.tag)#获取根的标签

1.遍历xml文档

for child in root:
    print(child.tag, child.attrib)#打印遍历内容的标签和属性值
    for i in child:
        print(i.tag, i.text,i.attrib)#如果有多层的话可以多加几层for

2.遍历指定的节点

for node in root.iter('year'):
    print(node.tag, node.text)

3.修改

#先修改,之后再写入
for node in root.iter('year'):
    new_year = 2018
    node.text = str(new_year)
tree.write("xmltest.xml")

4.删除

for country in root.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
        root.remove(country)
tree.write('output.xml')

猜你喜欢

转载自blog.csdn.net/qq_41901915/article/details/82633176