1

I have an XML file, which I would like to convert / export to a csv(-like) format.

Example:

<root>
  <child>
    <Name>John</Name>
    <Surname>Doe</Surname>
    <Name>George</Name>
    <Surname>Washington</Surname>
  </child>
</root>

ATM I do it like this (the print is for debug, nothing finished yet):

#!/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)

Current Output:

John
George
Doe
Washington

The result I would like to get:

John, Doe
George, Washington

Can anyone give me a hand here?

Thank you very much.

mattn
  • 7,571
  • 30
  • 54
joini
  • 11
  • 1
  • 2

1 Answers1

6

Use xpath and 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]))

If you want to call flexible with names of elements.

#!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]))
mattn
  • 7,571
  • 30
  • 54
  • When I write to csv it appends all in one row. Example: csv.write(",\n ".join([x.text for x in a])) – Vinod HC Jun 22 '15 at 10:45