Python XML到csv

时间:2017-03-10 13:22:39

标签: python csv xml-parsing

我正在2.6.4版本上学习Python 我要做的第一件事是尝试仅解析属性(orderno)的值并将其打印出来。 其次,我试图通过XML解析并从attribut“orderno”找到10238属性的值,但打印出整个项目为csv行,如“10238,1,Hasselblad 501 CM body,2355” 关于如何做的任何指示?

from xml.etree import ElementTree
tree = ElementTree.parse('sample.xml')
root = tree.getroot()

for item in root:
    first = item.find('orderno').text
    print first

数据:

<item> 
<orderno>10238</orderno>
<count>1</count>
<name>Hasselblad 501 CM body</name> 
<price>2355</price>
</item> 
<item> 
<orderno>20032</orderno>
<count>1</count>
<name>Carl Zeiss Planar Lens CB 2.8/80 mm</name>
<price>1233</price>
</item> 
<item>
<orderno>30212</orderno>
<count>1</count>
<name>Roll Film 120 Magazine A12</name>
<price>917</price>
</item> 

1 个答案:

答案 0 :(得分:1)

您基本上需要遍历所有子元素。 在这里,我通过列表理解迭代子项,并用逗号加入列表!

from xml.etree import ElementTree
tree = ElementTree.parse('sample.xml')
root = tree.getroot()

for item in root:
    print ','.join([sub_item.text for sub_item in item])

示例输出:

10238,1,Hasselblad 501 CM body,2355
20032,1,Carl Zeiss Planar Lens CB 2.8/80 mm,1233
30212,1,Roll Film 120 Magazine A12,917

希望它有所帮助!