I am using lxml in Python to parse an XML file. The file contains records with elements. The first element is always there. However, the other elements are not always available in each record. If an element is not there I want to add a "None" entry to Elementx list. When I do that each element list has the same size and I can easily append new values in the for loop when these are not present in the previous list. How can i append a "None" value in the element list when the element is not available in the record?
The code looks like this:
Element1_list = []
Element2_list = []
.
.
ElementN_list = []
def repeat():
xmlfile = urllib2.urlopen("link.xml").read()
root = lxml.etree.fromstring(xmlfile)
# Grabbing the elements from the XML file, list are here not equal in size
Element1 = root.xpath('//Record/Element1/text()')
Element2 = root.xpath('//Record/Element2/text()')
.
.
ElementN = root.xpath('//Record/ElementN/text()')
i = 0
for element in Element1:
if element not in Element1_list:
Element1_list.append(Element1[i])
Element2_list.append(Element2[i])
.
.
ElementN_list.append(ElementN[i])
i = i + 1
repeat()
repeat()
Thanks in advance.