import lxml.etree as et
xml = et.parse("test.xml")
for node in xml.xpath("//neighbor"):
node.getparent().remove(node)
xml.write("out.xml",encoding="utf-8",xml_declaration=True)
使用elementTree,我们需要找到parents of the neighbor nodes,然后找到neighbor nodes inside that parent并删除它们:
^{pr2}$
两者都会给你:<?xml version='1.0' encoding='utf-8'?>
1
2008
141100
4
2011
59900
68
2011
13600
使用属性逻辑并修改xml,如下所示:x = """<?xml version="1.0"?>
1
2008
141100
4
2011
59900
68
2011
13600
"""
使用lxml:import lxml.etree as et
xml = et.fromstring(x)
for node in xml.xpath("//neighbor[not(@make) and not(@job) and not(@make)]"):
node.getparent().remove(node)
print(et.tostring(xml))
会给你:
1
2008
141100
4
2011
59900
68
2011
13600
ElementTree中的相同逻辑:from xml.etree import ElementTree as et
xml = et.parse("test.xml").getroot()
atts = {"build", "job", "make"}
for parent in xml.findall(".//neighbor/.."):
for child in parent.findall(".//neighbor")[:]:
if not atts.issubset(child.attrib):
parent.remove(child)
如果您正在使用iter:from xml.etree import ElementTree as et
xml = et.parse("test.xml")
for parent in xml.getroot().iter("*"):
parent[:] = (child for child in parent if child.tag != "neighbor")
你可以看到我们得到完全相同的输出:In [30]: !cat /home/padraic/untitled6/test.xml
#
1
2008
141100
4
2011
59900
68
2011
13600
In [31]: paste
def test():
import lxml.etree as et
xml = et.parse("/home/padraic/untitled6/test.xml")
for node in xml.xpath("//neighbor"):
node.getparent().remove(node)
a = et.tostring(xml)
from xml.etree import ElementTree as et
xml = et.parse("/home/padraic/untitled6/test.xml")
for parent in xml.getroot().iter("*"):
parent[:] = (child for child in parent if child.tag != "neighbor")
b = et.tostring(xml.getroot())
assert a == b
## End pasted text
In [32]: test()