Python Forum

Full Version: XML to table CSV
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I have an question about parsing a XML-file to a table in CSV. What script can I use to make the XML file into a CSV file with tables.

My XML file is like:
<xml version="1.0">
<Person>
<General>
<Date Value="22/1/2016" />
<Version Value="16.3.2.38" />
<Name Value="MyName" />
</General>
</Person>
<Person>
<General>
<Date Value="22/1/2016" />
<Version Value="16.3.2.38" />
<Name Value="MyName2" />
</General>
</Person>
</xml>

Till now I use the script:
import xml.etree.ElementTree as ET
import csv       

tree = ET.parse("mydir")
root = tree.getroot()

Residant_data = open('/tmp/ResidentData.csv','w')

csvwriter = csv.writer(Resident_data)
resident_head = []

count = 0
for member in root.findall('Resident'):
	resident = []
	address_list = []
	if count == 0:
		DateValue = member.find('Date Value').tag
		resident_head.append(DateValue)
		VersionValue = member.find('Version Value').tag
		resident_head.append(VersionValue)
		NameValue = member.find('Name Value').tag
		resident_head.append(NameValue)

		csvwriter.writerow(resident_head)
		count = count + 1

	DateValue = member.find('Date Value').text
	resident.append(GameDateValue)
	VersionValue = member.find('Version Value').text
	resident.append(VersionValue)
	NameValue = member.find('Name Value').text
	resident.append(NameValue)

	csvwriter.writerow(resident)
Resident_data.close()
The error I receive is:
Error:
Traceback (most recent call last): File "testallfilesv2.py", line 40, in <module> tree = ET.parse("mydir") File "C:\Python27\lib\xml\etree\ElementTree.py", line 1182, in parse tree.parse(source, parser) File "C:\Python27\lib\xml\etree\ElementTree.py", line 656, in parse parser.feed(data) File "C:\Python27\lib\xml\etree\ElementTree.py", line 1653, in feed self._raiseerror(v) File "C:\Python27\lib\xml\etree\ElementTree.py", line 1517, in _raiseerror raise err ParseError: junk after document element: line 179, column 6
Then xml parser cannot read the source. You need to look at line 179 in the file "mydir" to see what puzzles the parser.
Thanks for your quick answer, on row 179 the first XML ends with </xml>.
On row 180 a new one starts with <xml version="1.0">