首页 > 解决方案 > 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 &lt;b product="man"&gt;text&lt;/b&gt;...

这不是我需要的。这就是我想要获得的(大约)(:

<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 或多个元素,它会失败。

关于如何解决它的任何提示?

标签: pythonxmllxmlcode-snippets

解决方案


尝试:

>>> new_snippet = '<section>' + snippet + '</section>'
>>> section = ET.fromstring(new_snippet)

推荐阅读