删除元素,但不删除后面的文本

时间:2014-04-09 15:45:34

标签: python elementtree

我有一个类似的XML文件:

<root>
<a>Some <b>bad</b> text <i>that</i> I <u>do <i>not</i></u> want to keep.</a>
</root>

我想删除<b><u>元素(和后代)中的所有文本,然后打印其余文本。这就是我试过的:

from __future__ import print_function
import xml.etree.ElementTree as ET

tree = ET.parse('a.xml')
root = tree.getroot()

parent_map = {c:p for p in root.iter() for c in p}

for item in root.findall('.//b'):
  parent_map[item].remove(item)
for item in root.findall('.//u'):
  parent_map[item].remove(item)
print(''.join(root.itertext()).strip())

(我使用this answer中的食谱来构建parent_map)。当然,问题在于remove(item)我还删除了元素后面的文本,结果是:

Some that I

而我想要的是:

Some  text that I  want to keep.

有没有解决方案?

1 个答案:

答案 0 :(得分:1)

如果您最终没有更好地使用任何内容,则可以使用clear()代替remove()保留元素的尾部:

import xml.etree.ElementTree as ET


data = """<root>
<a>Some <b>bad</b> text <i>that</i> I <u>do <i>not</i></u> want to keep.</a>
</root>"""

tree = ET.fromstring(data)
a = tree.find('a')
for element in a:
    if element.tag in ('b', 'u'):
        tail = element.tail
        element.clear()
        element.tail = tail

print ET.tostring(tree)

打印(请参阅空bu标记):

<root>
<a>Some <b /> text <i>that</i> I <u /> want to keep.</a>
</root>

此外,这是使用xml.dom.minodom

的解决方案
import xml.dom.minidom

data = """<root>
<a>Some <b>bad</b> text <i>that</i> I <u>do <i>not</i></u> want to keep.</a>
</root>"""

dom = xml.dom.minidom.parseString(data)
a = dom.getElementsByTagName('a')[0]
for child in a.childNodes:
    if getattr(child, 'tagName', '') in ('u', 'b'):
        a.removeChild(child)

print dom.toxml()

打印:

<?xml version="1.0" ?><root>
<a>Some  text <i>that</i> I  want to keep.</a>
</root>