使用 LXML 插入元素并设置属性和文本

Insert element with LXML and set attribute and text

我想多次插入具有相同标签的元素,每次使用 LXML 插入不同的内容和属性。虽然插入元素很容易,但如何获取新创建的元素以设置其文本和属性?

text = ['First', 'Second', 'Third']

for i, t in enumerate(text):
    parent.insert(i, etree.Element('tspan')
    # Now, what object should I use to set text and attrib?

使用 ElementTree(不需要外部库)

import xml.etree.ElementTree as ET

xml = '''<root></root>'''
text = ['First', 'Second', 'Third']

root = ET.fromstring(xml)
for txt in text:
    sub = ET.SubElement(root,'tspan')
    sub.text = txt
ET.dump(root)

输出

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <tspan>First</tspan>
   <tspan>Second</tspan>
   <tspan>Third</tspan>
</root>