【发布时间】:2014-02-04 21:56:22
【问题描述】:
我正在尝试从具有以下两种形式之一的 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']”行,但这也不是我尝试的方式。
【问题讨论】:
标签: python xml elementtree parse-tree