I'm new to Python and XML and trying to parse through the file below in order to extract several elements. The issue is that some elements are empty (example customer xyz1 does not have any address information).
<CAT>
<Header>...</Header>
<Add>...</Add>
<Customer>
<Id_Customer>xyz1</Id_Customer>
<Segment>abc1</Segment>
<Event>
<Nature>info1</Nature>
<Extrainfo>info2</Extrainfo>
</Event>
</Customer>
<Customer>
<Id_Customer>zzwy</Id_Customer>
<Segment>c2</Segment>
<Adress>
<zipcode>77098</zipcode>
<street>belaire drive</street>
<number>5</number>
</Adress>
</Customer>
<Customer>...</Customer>
</CAT>
I'm looping through the following elements (Id_Customer, Segment, Extrainfo, zipcode, street) in order to build up a list that I will then export to a .csv file.
My code below generates the following output : [xyz1,abc1,info2,zzwy,c2 ..] while I would like elements not found to be input in the list as "empty" so that my list would contain : [xyz1,abc1,info2,empty,empty, zzwy,c2 ..]
Here is a sample of my code :
from xml.etree import ElementTree
import csv
list_prm = []
tree = ElementTree.parse('file.xml')
root = tree.getroot()
for elem in tree.iter():
if elem.findall('Id_Customer'):
list_prm.append(elem.text)
if elem.tag == 'Segment':
list_prm.append(elem.text)
if elem.tag == 'Extrainfo':
list_prm.append(elem.text)
if elem.tag == 'street':
list_prm.append(elem.text)
if elem.tag == 'zipcode':
list_prm.append(elem.text)
print(list_prm)
I would very much appreciate some help. (I can only use standard python library.)
None? Because there's no such thing as "empty". If you want your list to contain a placeholder, you have to decide what you want it to be - lists only contain objects, they don't know how to contain "nothing"