Python 如何从ElementTree中删除特定属性

Python 如何从ElementTree中删除特定属性,python,xml,elementtree,parse-tree,Python,Xml,Elementtree,Parse Tree,我试图从xml文件中删除具有以下两种形式之一的所有行: <attr key="filename"><string>[SOME_FILENAME]</string></attr> <attr key="line_number"><integer>[SOME_NUMBER]</integer></attr> 但输出不是我想要的,它改变了这一点: <attr key="filename">&l

我试图从xml文件中删除具有以下两种形式之一的所有行:

<attr key="filename"><string>[SOME_FILENAME]</string></attr>
<attr key="line_number"><integer>[SOME_NUMBER]</integer></attr>
但输出不是我想要的,它改变了这一点:

<attr key="filename"><string>[SOME_FILENAME]</string></attr>
<attr key="line_number"><integer>[SOME_NUMBER]</integer></attr>
[一些文件名]
[一些数字]
进入这个

<attr><string>[SOME_FILENAME]</string></attr>
<attr><integer>[SOME_NUMBER]</integer></attr>
[一些文件名]
[一些数字]
我宁愿把这两行都删掉


我也尝试过用parent.remove(child)替换“del child.attrib['key']”行,但我尝试的方法也不起作用。

这是因为您只删除属性,而不是元素本身

尝试:

<attr><string>[SOME_FILENAME]</string></attr>
<attr><integer>[SOME_NUMBER]</integer></attr>
    dict = {}
    for parent in tree.iter():
        for child in parent:
               if 'key' in child.attrib:
                       if child.attrib['key'] == 'phc.filename':
                               dict[child] = parent
                       elif child.attrib['key'] == 'phc.line_number':
                               dict[child] = parent

    for child in dict:
        parent = dict[child]
        parent.remove(child)