1

次の 2 つの形式のいずれかを持つ 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>

これらの行の両方を完全に削除したい場合。

また、「del child.attrib ['key']」行をparent.remove(child)に置き換えてみましたが、試した方法でも機能しません。

4

1 に答える 1