将 lxml etree 文本设置为带有标签的字符串

Set lxml etree text to string with tags

我对 lxml.etree 库有疑问。 我有一个像

这样的字符串
string = "this<a/>is<b/>nice"

我想将这个字符串设置为元素节点的文本。

node.text = string

但是每次我打印出节点的文本时,它都会像这样转义:

"this&lt;a\&gt;is&lt;b\&gt;nice"

那么如何设置文本使其不再转义?我做不到,例如用 node.tail 或任何东西,因为我在文本中有多个节点。

您可以做的是向字符串添加根元素以使其格式正确,然后使用 tostring() 对其进行解析。然后您可以将元素添加为目标元素的子元素。

一旦它到达了它应该在的位置,您可以使用 strip_tags() 删除临时根元素。

示例...

Python

from lxml import etree

doc = etree.fromstring("<doc/>")

print(f"doc before: \"{etree.tostring(doc).decode()}\"")

string = "this<a/>is<b/>nice"

fragment = etree.fromstring(f"<temp>{string}</temp>")
doc.append(fragment)
etree.strip_tags(doc, "temp")

print(f"doc after: \"{etree.tostring(doc).decode()}\"")

控制台输出

doc before: "<doc/>"
doc after: "<doc>this<a/>is<b/>nice</doc>"