Python实现对于xml文件中数据的增删改查

# -*- 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)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值