【问题标题】:How to remove specific attributes from an ElementTree如何从 ElementTree 中删除特定属性
【发布时间】: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


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-16
      • 2011-10-23
      • 2014-10-24
      • 1970-01-01
      • 2018-05-08
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多