# -*- coding: UTF-8 -*- import ete.cryptolib import ete.initete from xml.etree import ElementTree as ET #****************1 加载文件 tree = ET.parse('./CardData.xml') #****************2 获得根结点 root=tree.getroot() #****************3 按照路径寻找某个结点 #根据路径寻找某个结点的值 AID=root.find('GPData/CurrentAID') print(AID.text) #直接寻找某个结点的值 AIDText=root.findtext('GPData/CurrentAID') print("AIDTEXT+ "+AIDText) #更改某个结点的值 AID.text="A0000003330101" #****************4 获得某个结点的子节点的信息 GP_Node=root.find('GPData') #返回的符合条件的所有结点的集合(数组) childens=GP_Node.iter() for child in childens: print(child.text) print(child.tail) #****************5 对结点属性的访问 AIDList=root.find('GPData/AIDList') #根结点下的所有子节点 childens=AIDList.iter(tag="AppletAID") #访问属性 响应的可以根据属性查找值 for child in childens: items=child.attrib #判断某个结点的某个属性是不是存在 if items.get('Number'): mynumber=items["Number"] print("my number is "+mynumber) mystate=items["State"] print("my mystate is "+mystate) #****************5 在指定的目录下增加一个,复制原有结点 currentAPP=root.find('AppletData/CurrentTranscation') #复制原有结点到指定结点 tempnode=root.find('AppletData/CurrentTranscation/ATC') currentAPP.append(tempnode) #****************6 在指定的目录下增加一个,创建一个新的结点并添加 #构建新的几点并添加 #实例化一个结点 employee=ET.Element('employee',{'id':'99'}) #Element(tag, attrib={}, **extra) employee.text='Hello World' #这一行不可以少要不然会很难看,结点与它的父节点之间不会构成层级关系 employee.tail="\n" root.append(employee) #在指定位置增加 root.insert(1,employee) tester=ET.Element('tester',{'id':'100'}) #Element(tag, attrib={}, **extra) tester.text='Hello tester' #这一行不可以少要不然会很难看,结点与它的父节点之间不会构成层级关系 tester.tail="\n" root.append(tester) #****************7 保存文件 tree.write('CardData.xml',encoding = "utf-8",xml_declaration=True) #****************8 删除几点 root.remove(employee) root.remove(tester) tree.write('CardData2.xml',encoding = "utf-8",xml_declaration=True)
Python实现对于xml文件中数据的增删改查
最新推荐文章于 2023-01-17 16:36:58 发布