我有一个XML文件,我想将其转换/导出为csv(类似)格式。
示例:
<root>
<child>
<Name>John</Name>
<Surname>Doe</Surname>
<Name>George</Name>
<Surname>Washington</Surname>
</child>
</root>
ATM我这样做(打印用于调试,还没有完成):
#!/bin/python env
import xml.etree.ElementTree as etree
tree = etree.parse('./foobar.xml')
root = tree.getroot()
elements = ('Name', 'Surname')
for i in elements:
for i in root.iter(i):
print(i.text)
当前输出:
John
George
Doe
Washington
我想得到的结果:
John, Doe
George, Washington
有人可以帮我一把吗?
非常感谢。
答案 0 :(得分:6)
使用xpath和zip()。
#!python
import xml.etree.ElementTree as etree
root = etree.parse('./foobar.xml').getroot()
for a in zip(root.findall("child/Name"), root.findall("child/Surname")):
print(", ".join([x.text for x in a]))
如果您想使用元素名称调用灵活方式。
#!python
import xml.etree.ElementTree as etree
child = etree.parse('./foobar.xml').getroot().find('child')
elements = ('Name', 'Surname')
for a in zip(*[child.findall(x) for x in elements]):
print(", ".join([x.text for x in a]))