I have been trying to write xml code to retrieve the data in csv format
When I use i.text
it gives all data in one line
I am expecting data should be in csv format
My code :
import xml.etree.ElementTree as ET
data='''
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
</breakfast_menu>
'''
xml_parser = ET.fromstring(data)
count_of_child_element = []
cnt = 0
for i in xml_parser.getiterator():
if i.tag == 'food':
count_of_child_element.append(cnt)
cnt = cnt 1
for indx in range(len(count_of_child_element)):
for x in xml_parser[indx]:
print(x.text,end=' ')
print()
Expected output :
Belgian Waffles,$5.95,Two of our famous Belgian Waffles with plenty of real maple syrup,650
Strawberry Belgian Waffles,$7.95,Light Belgian waffles covered with strawberries and whipped cream,900
CodePudding user response:
This should give the output you are looking for:
xml_parser = ET.fromstring(data)
for indx in range(len(xml_parser)):
for x in range(len(xml_parser[indx])):
e = xml_parser[indx][x]
print(e.text, end="")
if x != len(xml_parser[indx]) - 1:
print(",", end="")
print()