for loop in python to create list in lxml in python

To create a list in lxml using a for loop in Python, you can follow these steps:

  1. Import the lxml library and create a new XML element:
main.py
from lxml import etree

root = etree.Element("root")
53 chars
4 lines
  1. Create a list of values that you want to add to the XML element:
main.py
values = ["value1", "value2", "value3"]
40 chars
2 lines
  1. Use a for loop to iterate through each value in the list and add it to the XML element using the etree.SubElement method:
main.py
for val in values:
    elem = etree.SubElement(root, "myelement")
    elem.text = val
86 chars
4 lines
  1. Finally, print the resulting XML element to see the list of values that you created:
main.py
print(etree.tostring(root, pretty_print=True))
47 chars
2 lines

The full code would look something like this:

main.py
from lxml import etree

root = etree.Element("root")

values = ["value1", "value2", "value3"]

for val in values:
    elem = etree.SubElement(root, "myelement")
    elem.text = val

print(etree.tostring(root, pretty_print=True))
229 chars
12 lines

related categories

gistlibby LogSnag