【问题标题】:python: remove given xml tagpython:删除给定的xml标签
【发布时间】:2020-02-23 16:13:32
【问题描述】:

早上好, 我试图删除标签标题但我没有成功。 我的代码在下面,它不会产生错误但不会删除标题标签。 提前谢谢你,

<xml>
   <Heading>
     <tmp> a1</tmp>
     <tmp2> a2 </tmp2>
   </Heading>
   <data>
      <db> Id0123 </db>
      <db1>
         <x1> abc </x1>
         <x2> dze </x2>
     </db1>
     <db2>
         <x1> abc2 </x1>
     </db2>
   </data>
</xml>

Expected_Output

<xml>
   <data>
      <db> Id0123 </db>
      <db1>
           <x1> abc </x1>
           <x2> dze </x2>
      </db1>
      <db2>
           <x1> abc2 </x1>
      </db2>
   </data>
</xml>

代码

xmlTree = parse("File.xml")
for xe in xmlTree.findall("xml"): 
    for elementx in xe.findall('Heading'): 
        xe.remove(elementx)                   

【问题讨论】:

标签: python python-3.x xml-parsing findall


【解决方案1】:

使用您的 xml 示例,找到要删除的元素并对其进行迭代。

import xml.etree.ElementTree as ET
xmlTree = ET.fromstring(s)
with open('foo.xml') as f:
    xmlTree = ET.parse(f)
for el in xmlTree.getiterator('xml'):
    for thing in el.getiterator('Heading'):
        print(thing.tag,thing.attrib)
        el.remove(thing)

【讨论】:

  • 感谢您的回复。我收到此错误 AttributeError: 'ElementTree' object has no attribute 'remove'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 2013-05-19
  • 2021-08-12
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多