lxml.etree insert elements into element.text

▼魔方 西西 提交于 2019-12-02 02:04:08

You could make your input string a well-formed XML document (with text as the root element) and parse that into an Element object using fromstring(). Then append it to the parent.

from lxml import etree as et

s1 = """foo bar <pb n="42"/> parrots like <pb n="43"/> eggs and spam"""
s2 = "<text>{0}</text>".format(s1)

text = et.fromstring(s2)
root = et.Element('root')
root.append(text)

et.dump(root)

Output:

<root>
 <text>foo bar <pb n="42"/> parrots like <pb n="43"/> eggs and spam</text>
</root>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!