import xml.etree.ElementTree as ET #起别名 tree=ET.parse('a.xml') root=tree.getroot() # 对于任何标签都有三个特征:标签名,标签属性,标签的文本内容 print(root.tag) print(root.attrib) print(root.text) print(list(root.iter('year')))#全文搜索,找到所有 for year in root.iter('year'):#找到所有的year 遍历出所有的信息 print(year.tag) print(year.attrib) print(year.text) print('='*100) print(root.find('country').attrib)#在root的子节点找,只找一个,打印标签的属性{'name': 'Liechtenstein'} print([country.attrib for country in root.findall('country')])#root 的子节点找找到所有的标签属性[{'name': 'Liechtenstein'}, {'name': 'Singapore'}, {'name': 'Panama'}] # 1.查 # 遍历整个文档 for country in root: print('====>国家%s'%country.attrib) for item in country: print(item.tag) print(item.attrib) print(item.text) # 2,改 for year in root.iter('year'): print(year.tag) year.attrib={'update':'yes'} year.text=str(int(year.text)+1)#所有的值为字符串类型所以要转换 tree.write('a.xml') # 3.增 for country in root: rank=country.find('rank') if int(rank.text)>50:#查看rank的文本类容是否大于50 tag=ET.Element('egon')#建一个标题 tag.attrib={'update':'yes'}#赋值一个标签属性 tag.text='NB'#建一个文本类容 country.append(tag)#添加文件到country内 tree.write('a.xml')#写入文件 # 4.删 for country in root: tag=country.find('egon') if tag is not None:#出来的tag值为内存地址但是为none,所以如此 print('====>') country.remove(tag) tree.write('a.xml')
python的xml模块
最新推荐文章于 2023-09-12 20:14:20 发布