kamfulebu kamfulebu - 1 month ago 7
Python Question

Python XML - Create n SubElements

How to create n SubElements? Number of elements was previously defined by the given value (count). Names of elements and values in them are the same for all elements.
Example:

<root>
<selem>-9999</selem>
<selem>-9999</selem>
<selem>-9999</selem>
<selem>-9999</selem>
.
.
.
n
</root>


I tried something like the

file_count = open('file_count.xml','r')
data = file_count.read()
file_count.close()
dom = parseString(data)
count = len(dom.getElementsByTagName('timePosition'))

no_data = '-9999'
top = etree.Element('root')
children = [
etree.SubElement(top, 'selem').text = no_data
for i in xrange(count)
]
top.extend(children)
print etree.tostring(top)
no_data_xml = etree.ElementTree(top)
no_data_xml.write(new.xml')


Tnx

Answer

You can't put statements such as variable assignments inside a list comprehension. Just use a plain for loop:

for i in xrange(count):
    elem = etree.SubElement(top, 'selem')
    elem.text = no_data
    top.append(elem)