我一直在嘗試撰寫 xml 代碼來檢索 csv 格式的資料
當我使用i.text它時,它會在一行中提供所有資料,我期望資料應該是 csv 格式
我的代碼:
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()
預期輸出:
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
uj5u.com熱心網友回復:
這應該給出您正在尋找的輸出:
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/471874.html
