python - 如何创建带有文本和标签的元素?

标签 python python-3.x lxml

我已经创建了下一个 XML:

item = E('p') # <p/>

现在我需要将下一个内容放入其中:

text = "some <bold>text</bold>"

# item.append(text) 
# TypeError: Argument 'element' has incorrect type (expected lxml.etree._Element, got str)

# item.append(fromstring(text)) 
# lxml.etree.XMLSyntaxError: Start tag expected, '<' not found, line 1, column 1

我需要下一个 XML 节点作为结果:

<p>some <bold>text</bold></p>

如何正确地做到这一点?

最佳答案

您需要创建子元素:

from lxml import etree

root = etree.Element("p")
root.text = 'some'

bold = etree.SubElement(root, 'bold')
bold.text = 'text'

print (etree.tostring(root))

返回:

<p>some<bold>text</bold></p>

关于python - 如何创建带有文本和标签的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46927427/

相关文章:

python - Django Rest Framework 中的 API 查询

python-3.x - 为什么 asyncio.create_task 不运行该方法?

python - python多处理队列中的死锁

python - 流解析 Wiki Xml 转储

python - lxml 失败的 XPath

python - 将 Python 的 grpcio 模块嵌入到 Bazel 项目中

python - 在 Python Kivy 中查找程序使用的总内存的方法

Python3 - 如何将字符串转换为十六进制

python - 有没有办法找到多个计时器中哪一个引发了异常?

python - 'charmap' 编解码器无法解码位置 33222 : character maps to <undefined> 中的字节 0x8d