I want to convert the following XML file:
<data>
<level_1 name="employment">
<level_2 name="sub-employment">
<indicator>ind1</indicator>
<indicator>ind2</indicator>
</level_2>
<level_2 name="sub-employment2">
<indicator>ind3</indicator>
</level_2>
</level_1>
<level_1 name="health">
<level_2 name="sub-health">
<level_3 name="sub-sub-health">
<indicator>ind4</indicator>
</level_3>
</level_2>
</level_1>
</data>
into a Pandas dataframe with a result similar to:
level_1 level_2 level_3 indicator
0 employment sub-employment None ind1
1 employment sub-employment None ind2
2 employment sub-employment2 None ind3
3 health sub-health sub-sub-health ind4
I have used the following code after import xml.etree.cElementTree as et and import pandas as pd:
def getvalueofnode(node):
""" return node text or None """
return node.text if node is not None else None
def main():
""" main """
parsed_xml = et.parse("tree.xml")
dfcols = ['level_1', 'level_2', 'level_3', 'indicator']
df_xml = pd.DataFrame(columns=dfcols)
for node in parsed_xml.getroot():
name = node.attrib.get('name')
level_2 = node.find('level_2')
level_3 = node.find('level_3')
indicator = node.find('indicator')
df_xml = df_xml.append(
pd.Series([name, getvalueofnode(level_2), getvalueofnode(level_3),
getvalueofnode(indicator)], index=dfcols),
ignore_index=True)
print(df_xml)
main()
but I am getting the wrong result:
level_1 level_2 level_3 indicator
0 employment \n None None
1 health \n None None
What am I doing wrong here?