要使用lxml删除元素时要删除所有子项

时间:2018-12-29 22:10:19

标签: python lxml

似乎无法弄清楚如何删除元素'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()

1 个答案:

答案 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兼容)