Parse XML and get data of certain tags to CSV Python



I'm trying to parse the following XML file and get output to a CSV file like below. I tried elementree. However, it prints in output.


trial.xml



<?xml version="1.0">
<!-- random text -->
<!-- random text -->
<meta>
<valID>
<ValueID>age</ValueID>
<desc>Physical attributes | Age at time of evaluation</desc>
<group>
<ord>1</ord>
<name>0 - &lt;5</name>
<min>0</min>
<mininc>TRUE</mininc>
<max>5</max>
<maxinc>FALSE</maxinc>
</group>
<group>
<ord>2</ord>
<name>5 - &lt;10</name>
<min>5</min>
<mininc>TRUE</mininc>
<max>10</max>
<maxinc>FALSE</maxinc>
</group>
</valID>
</meta>


output.csv



ValueID,name,min,maxinc
age,1,0-<5,0,5
age,5-<10,5,10


Code I tried:



from xml.etree import ElementTree
document = ElementTree.parse( 'trial.xml' )
for d in document.findall('meta/valID/ValueID'):
print d.text

No comments:

Post a Comment