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

时间:2019-11-20 15:17:17

标签: python xml lxml elementtree

我对lxml.etree库有问题。 我有一个像这样的字符串

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

并且我想将此字符串设置为元素节点的文本。

node.text = string

但是每次我打印出该节点的文本时,它都是这样逃脱的:

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

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

1 个答案:

答案 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>"
相关问题