我对lxml.etree库有问题。 我有一个像这样的字符串
string = "this<a/>is<b/>nice"
并且我想将此字符串设置为元素节点的文本。
node.text = string
但是每次我打印出该节点的文本时,它都是这样逃脱的:
"this<a\>is<b\>nice"
那么我该如何设置文本使其不再被转义?我做不到使用node.tail或其他任何东西,因为文本中有多个节点。
答案 0 :(得分:2)
您可以做的是在字符串中添加根元素以使其格式正确,然后使用tostring()
对其进行解析。然后,您可以将Element添加为目标元素的子元素。
在原定位置,您可以使用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>"