python - lxml:在 etree.SubElement 中包含一个字符串(可能包含一个 xml 片段)
问题描述
我正在用 lxml 编写一个 XML 文件。在给定的时刻,我必须将字符串变量的内容“粘贴”为元素的“文本”。该字符串可以是纯文本或包含任意数量的有效 xml 标记(当然是嵌套的),并且假定它会被正确标记。
from lxml import etree as ET
snippet = "This is a <b product="man">text</b><b product="aps">test</b> or a list <ul><li>1</li><li>2</li></ul> and should work"
tree = ET.Element('topic')
section = ET.SubElement(tree, 'section')
section.text = <xml converted snippet>
我确实知道section.text不是插入它的方式,因为然后代码片段会转换为:
This is a <b product="man">text</b>...
这不是我需要的。这就是我想要获得的(大约)(:
<topic>
<section>This is a <b product="man">text</b><b product="aps">test</b>
or a list
<ul>
<li>1</li>
<li>2</li>
</ul>
and should work
</section>
</topic>
我曾尝试使用ET.fromstring(snippet)但如果它找到嵌套的 xml 或多个元素,它会失败。
关于如何解决它的任何提示?
解决方案
尝试:
>>> new_snippet = '<section>' + snippet + '</section>'
>>> section = ET.fromstring(new_snippet)
推荐阅读
- node.js - when running npm install I am getting back npm ERR! code E404
- python - 在基于 Python 的应用程序中从 Kubernetes 读取机密
- c# - Dynamics 365 - 具有不存在条件的 Linq 查询
- java - Azure (Java) BlobClient.uploadWithResponse 何时准备好上传?
- r - 在模拟 LGCP kppm 时指定设定的点数
- csv - 从 csv 文件应用年龄分布时出错
- perl - 如何匹配制表符分隔的矩阵文件中的字符串列表
- python - (JIT) 使用 FFI 库调用编译 Python 代码
- android - 启用 ProGuard 的签名 apk 崩溃
- c++ - 如何在 vscode 中添加 boost 库