我有一个 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.
有什么解决办法吗?
请您参考如下方法:
如果你最终不会使用更好的东西,你可以使用 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)
打印(见空的 b 和 u 标签):
<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>
