似乎无法弄清楚如何删除元素'framelineName'和所有附加的子元素。 else语句的底部区域将仅删除元素framelineName。我还想删除'line','left'和'right'。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lxml import etree as ET
def cash_rules_everything_around_me():
shaolin = ET.SubElement(root, "Shaolin")
wtClan = ET.SubElement(root, "wtClan")
wtClan.set('StatenIsland', 'NYC')
RZA = ET.SubElement(shaolin, "RZA")
RZA.set('StatenIsland', 'NYC')
gf = ET.SubElement(RZA, "GhostfaceKillah")
rk = ET.SubElement(RZA, "Raekwon")
wutang = "36 chambers"
for wu in wutang:
if wu != "36 chambers":
wtClan.text = "A Tribe Called Quest"
else:
for w in root.xpath("//wtClan [@StatenIsland=\'NYC']"):
w.getparent().remove(w)
tree = ET.ElementTree(root)
tree.write("wutang.xml", pretty_print=True, xml_declaration=True, encoding='UTF-8')
if __name__ == '__main__':
root = ET.Element("HipHop")
cash_rules_everything_around_me()
答案 0 :(得分:0)
要删除元素,您需要实际的元素对象而不是列表,列表不是lxml的xpath
的返回。考虑findall
遍历元素并将xpath
逻辑移至if
语句:
...
# ITERATE THROUGH A LIST (NOT STRING)
for wu in [wutang]:
if wu != "36 chambers":
wtClan.text = "A Tribe Called Quest"
else:
for w in root.findall("//wtClan"):
if w.attributed['StatenIsland']
root.remove(w)
tree = ET.ElementTree(root)
tree.write("wutang.xml", pretty_print=True,
xml_declaration=True, encoding='UTF-8')
Rextester demo (使用内置的etree
,但与lxml
兼容)