我正在尝试使用 lxml 将文本插入到 XML 中。该文本包含 XML,它应该成为它插入的 XML 的一部分。
以下代码不起作用:
from lxml import etree
tree = etree.fromstring('<tag><src></src><src></src></tag>')
new_mix = 'This <x id="1"/> rocks the <x id="2"/>!'
for src in tree.findall('.//src'):
src.append(etree.fromstring(new_mix))
print(etree.tostring(tree))
lxml.etree.XMLSyntaxError: Start tag expected, '<' not found, line 1, column 1
如果我将
<p></p>
父标签添加到 new_mix
,那么它就变成 '<p>This <x id="1"/> rocks the <x id="2"/>!</p>'
,它可以工作:
b'<tag><src><p>This <x id="1"/> rocks the <x id="2"/>!</p></src><src><p>This <x id="1"/> rocks the <x id="2"/>!</p></src></tag>'
但是如何在保留内容的同时避免或删除
<p>
或任何其他父标签?
你可以伪造它......
首先,将
new_mix
更改为
new_mix = '<src>This <x id="1"/> rocks the <x id="2"/>!</src>'
然后将你
for loop
更改为
for src in tree.findall('.//src'):
t = src.getparent()
t.remove(src)
t.append(etree.fromstring(new_mix))
这应该可以帮助您实现目标,至少基于示例 xml。