如何删除或删除server1的所有条目,包括标记?我试过使用etree删除功能,但没有帮助。
<hosts>
<host instances="" name="*" roles="alpha">
<tags/>
</host>
<host instances="" name="server1" id="alpha,beta">
<tags>
<tag app-id="1" instance="1" name="alpha"/>
<tag app-id="2" instance="2" name="beta"/>
</tags>
</host>
<host instances="" name="server2" id="beta,gama">
<tags>
<tag app-id="1" instance="1" name="beta"/>
<tag app-id="2" instance="2" name="gama"/>
</tags>
</host>
</hosts>
def main1(file=outfile):
tree = et.parse(file)
root = tree.getroot()
thingy = root.find('hosts')
for thing in thingy:
if "server1" in thing.get('name'):
root.remove(thing)
#thingy.remove(thing)
print thingy发布于 2015-12-17 13:16:55
需要父对象从HTML/XML中删除其子对象。
使用getparent()方法获取父函数,然后使用remove()方法删除其chid标记。
Demo
>>> import lxml.etree as PARSER
>>> root = PARSER.fromstring(data)
>>> root.xpath("//hosts/host[@name='server1']")
[<Element host at 0xb6d2ce6c>]
>>> a = root.xpath("//hosts/host[@name='server1']")
>>> for i in a:
... pp = i.getparent()
... pp.remove(i)
...
>>> PARSER.tostring(root, method="xml")A. find返回用于以下代码的None对象。
>>> thingy = root.find('hosts')
>>> thingy这应该是thingy = root.find('host')
B.使用xpath方法获取目标标记。
https://stackoverflow.com/questions/34335325
复制相似问题