python添加lxml库_Python Lxml:添加和删除标签

本文介绍了一种在XML树中根据布尔标志添加或删除标签的方法,并讨论了在实现过程中遇到的问题及解决策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bd96500e110b49cbb3cd949968f18be7.png

I am attempting to add and remove tags in an xml tree (snip below). I have a dict of boolean values that I use to determine whether to add or remove a tag. If the value is true, and the element does not exist, it creates the tag (and its parent if it doesn't exist). If false, it deletes the value.

However, it doesn't seem to work, and I can't find out why.

27913.769923

5174.627773

P03.png

snow.png

Dvaered

10.000000

1

P

100

Fooo

(null)

Code:

def writeflagX(self, root, x_path, _flag):

''' Writes flag to tree: deletes if false and already exists

and adds if true but doesn't exist yet)

'''

try:

if root.xpath(x_path):

if not self.flag[_flag]:

#delete value

temp1 = root.xpath(x_path)

temp1.getparent().remove(temp1)

print "removed"

#yeah, pretty ugly

except AttributeError:

#element does not exist, so create it if true value is here

#first, see if parent tag of list items exists, create it if neccesary

#split xpath into leader and item

leader = x_path.split("/")[0]

print leader

item = x_path.split("/")[1]

try:

if root.xpath(leader): #try to see if parent tag exists

child = etree.Subelement(root.xpath(leader), item)

print "no errors"

print "not caught"

except AttributeError:

l2 = leader.split("/")[0]

print l2 + " hi"

try:

l3 = leader.split("/")[1]

if l3: #if this tag is not a direct child of the root

child1 = etree.Subelement(root.xpath(l2), l3)

child1.append(etree.Element(item))

print "no dex error"

except IndexError: #if this tag is a direct child of the root

print "dex error"

child2 = etree.SubElement(root, l2)

def writeALLflagsX(self, _root):

'''Uses writeflagX and sets all the flags

'''

for k in self.flag:

self.writeflagX(_root, self.flagPaths[k], k)

I try to change the mission flag from false to true, and the refuel flag from true to false.

#Change Missions to true and refuel to false

foo = Asset()

###parsing code###

foo.alist["Adham"].flag["Is_missions"] = True

foo.alist["Adham"].flag["Is_refuel"] = False

foo.alist["Adham"].writeALLflagsX(foo.alist["Adham"].node)

foo.writeXML("output.xml")

I am stumped. The missions tag does not get added and the refuel tag does not get deleted.

Does this have something to do with me nesting the try/except statements?

Edit:

Ok, fixed the deleting problem by using a for loop as suggested:

temp1 = root.xpath(x_path)

for n in temp1:

n.getparent().remove(n)

Still can't add a node.

I think I am going to set up a new question that is simpler, since this is too convoluted.

解决方案

There are several things could be improved in the code:

node.xpath returns the list of nodes - i.e. you can't do root.xpath(path).getparent(), check the list and take the node #0 if you're sure that it should exist (you node deletion code uses this);

when working with attributes try using node.attrib dictionary. Working with attributes becomes as easy as modifying python dictionary (del node.attrib[attr] and node.attrib[attr] = value, make sure the value is str though);

it might be useful to use etree.XML('') for creating new nodes.

Hope it helps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值