1

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
1
  • 1
    Why in world would you expect the data to be in CSV format? Commented May 9, 2022 at 11:22

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

can you elaborate your code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.