Home > Software design >  Insert element with LXML and set attribute and text
Insert element with LXML and set attribute and text

Time:09-29

I want to insert elements with the same tag multiple times, with different contents and attribute each time with LXML. While it's easy to insert the element, how do I fetch the newly created element to set its text and attributes?

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?

CodePudding user response:

Using ElementTree (no external library is required)

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)

output

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