如何从ElementTree中删除特定属性

时间:2014-02-04 21:56:23

标签: python xml elementtree parse-tree

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

<attr key="filename"><string>[SOME_FILENAME]</string></attr>
<attr key="line_number"><integer>[SOME_NUMBER]</integer></attr>

现在我的代码看起来像这样:

for parent in tree.iter():
    for child in parent:
           if 'key' in child.attrib:
                   if child.attrib['key'] == 'phc.filename':
                           del child.attrib['key']
                   elif child.attrib['key'] == 'phc.line_number':
                           del child.attrib['key']

但输出不是我想要的,它正在改变这个:

<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']”行,但这并不像我尝试的那样。

1 个答案:

答案 0 :(得分:1)

那是因为你只删除了属性,而不是元素本身

尝试:

    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)