如何从 xml 数据中获取 csv 格式的数据
How to get data in csv format from xml data
我一直在尝试编写 xml 代码来检索 csv 格式的数据
当我使用 i.text
时,它在一行中给出了所有数据
我希望数据应该是 csv 格式
我的代码:
import xml.etree.ElementTree as ET
data='''
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>.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>.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,.95,Two of our famous Belgian Waffles with plenty of real maple syrup,650
Strawberry Belgian Waffles,.95,Light Belgian waffles covered with strawberries and whipped cream,900
这应该会给出您正在寻找的输出:
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()
我一直在尝试编写 xml 代码来检索 csv 格式的数据
当我使用 i.text
时,它在一行中给出了所有数据
我希望数据应该是 csv 格式
我的代码:
import xml.etree.ElementTree as ET
data='''
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>.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>.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,.95,Two of our famous Belgian Waffles with plenty of real maple syrup,650
Strawberry Belgian Waffles,.95,Light Belgian waffles covered with strawberries and whipped cream,900
这应该会给出您正在寻找的输出:
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()