gpt4 book ai didi

lxml - 使用 lxml 删除带有文本的元素

转载 作者:行者123 更新时间:2023-12-01 11:56:22 26 4
gpt4 key购买 nike

我有以下xml文件

<xml>
<network id="5">
<nodelist>
<IP>10.10.0.135::3111</IP>
<IP>10.10.0.130::3111</IP>
<IP>10.10.0.129::3111</IP>
<IP>10.10.0.129::3111</IP>
</nodelist>
<nodelist2/>
</network>
</xml>

我想删除 IP 为 10.10.0.129 且网络 id=5 的所有元素。我怎样才能在 lxml 中做到这一点?

目前,我正在尝试使用 xpath 查找节点并尝试将其删除。

但是,

netid=xml.xpath("network[@id=%s]/nodelist/IP[contains(text(),%s)]"%(id,node))

给我错误 lxml.etree.XPathEvalError: Invalid expression

最佳答案

我是一名 python 程序员,所以我用 python 2.7 编写了它。如果你需要使用不同的语言,你将不得不自己移植它,因为我除了 Python 什么都不做。

请注意,虽然这看似处理 xpath,但我的大部分处理是使用 python 完成的。

import lxml.etree as etree  #import etree, like c's include

def delete(xml,networkid,ipaddr):
tree = etree.fromstring(xml)
networks = tree.findall('.//network[@id="%s"]'%str(networkid)) #I think you forgot the quotes in your insertion.
for network in networks: #for each network that has id='5'.
ips = network.findall('.//IP') #All the IP elements under the network
for ip in ips: #iterating through a list of ips
if ipaddr in ip.text: #if ipaddr is inside the text, even if a port is appended
ip.getparent().remove(ip) #the ip's parent (nodelist) removes the ip element
return tree # I give you the tree


s = r'''<xml> #Here's your original xml
<network id="5">
<nodelist>
<IP>10.10.0.135::3111</IP>
<IP>10.10.0.130::3111</IP>
<IP>10.10.0.129::3111</IP>
<IP>10.10.0.129::3111</IP>
</nodelist>
<nodelist2/>
</network>
</xml>'''

res = delete(s,'5','10.10.0.129') #here's the result
print res #and it's a tree.
print list(res.iter()) #so I print all the items under it.
print etree.tostring(res) #and you have your edited xml.

关于lxml - 使用 lxml 删除带有文本的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6840423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com