遍历xml删选_如何遍历xml数据以使用lxml删除下一个重复元素

fromlxmlimportetreefromioimportStringIOxml='''

data1

data2

data3

data4

data5

data6

'''# this is to simulate that above xml was read from a filefile=StringIO(unicode(xml))# reading the xml from a filetree=etree.parse(file)root=tree.getroot()# iterate over all "b" elementsforelementinroot.iter('b'):# checks if the last "b" element has been reached.# on last element it raises "AttributeError" eception and terminates the for looptry:# attributes of actual elementelem_attrib_ACT=element.attrib# attributes of next elementelem_attrib_NEXT=element.getnext().attribexceptAttributeError:# if no other element, breakbreakprint('attributes of ACTUAL elem:',elem_attrib_ACT,'attributes of NEXT elem:',elem_attrib_NEXT)ifelem_attrib_ACT==elem_attrib_NEXT:print('next elem is duplicate of actual one -> remove it')# I would like to remove next element but this approach is not working# if you uncomment, it removes the elements of "data2" but stops# how to remove the next duplicate element?#element.getparent().remove(element.getnext())else:print('next elem is not a duplicate of actual')print('result:')print(etree.tostring(root))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值